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
Community moderators have prevented the ability to post new answers.
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")
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.