Missed Team ’24? Catch up on announcements here.

×
Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Retrieving errorMessages when a call to the rest api fails (Using HttpURLConnection)

Nelson D March 13, 2013

Hi,

Is there a way to get the errorMessages when a call to the REST API using Java fails ?

I am using Java and the HttpURLConnection class to connect and post to the REST API. When the HttpURLConnection fails, I get the response code but would like to have the errorMessages. Is there a way to get this information ?

Regards,

Nelson

1 answer

1 accepted

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

0 votes
Answer accepted
Aleksander Mierzwicki
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
March 18, 2013

If you need to get response content when there is non successfull response code (!= 200) you can use connection.getErrorStream() stream. For example:

final URL url = new URL("http://127.0.0.1:8091/jira/rest/api/latest/user");
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");

if (connection.getResponseCode() != 200) {
	final String errorContent = IOUtils.toString(connection.getErrorStream());
	throw new RuntimeException(String.format("GET failed with %s code and %s message. Response content is:\n%s",
			connection.getResponseCode(), connection.getResponseMessage(), errorContent
	));
}

final String content = IOUtils.toString(connection.getInputStream());
System.out.println(String.format("Connection successful, the response is:\n%s", content));
connection.disconnect();

In this case I got exception due to 401 error returned by the server:

java.lang.RuntimeException: GET failed with 401 code and Unauthorized message. Response content is:
{"errorMessages":["You are not authenticated. Authentication required to perform this operation."],"errors":{}}
	at it.TST1.testName(TST1.java:31)

You can also create new JSONObject from that body, and you'll be able to get the error messages by using get method: new JSONObject(errorContent).get("errorMessages")

TAGS
AUG Leaders

Atlassian Community Events