HttpURLConnection: how to read payload of 400 response

user1578796 picture user1578796 · Jul 12, 2014 · Viewed 11.9k times · Source

I use the following code to send a JSON request to my web service, and, for a bad request I return a 400 message code along with a detailed JSON error response in the payload.

I do not understand how I could possibly retrieve this payload on the client side when using HttpURLConnection, as it immediately throws an IOException and the connection's InputStream is null.

HttpURLConnection connection = this.connect(url);
connection.setRequestMethod(method);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonMessage);
InputStream is = null;
try {
    is = connection.getInputStream(); // IOException is thrown, how can I still get payload??
} catch (Exception e) {
} 
String response = getStringFromInputStream(is);

Also tried to use getErrorStream(), but this was containing Apache Tomcat's default error page rather than the payload I can see when, e.g. I use a visual REST API client.

Answer

user1578796 picture user1578796 · Aug 5, 2014

I have found numerous threads which state that HTTPUrlConnection simply does not transfer the standard payload if the status code is an error message, e.g. stackoverflow.com/questions/21526082/…, also please refer to this blog in case tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection.

I ended up using the much more powerful Apache package.