Dan Fabulich Dan Fabulich - 1 year ago 71
Java Question

Read error response body in Java

In Java, this code throws an exception when the HTTP result is 404 range:

URL url = new URL("http://stackoverflow.com/asdf404notfound");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getInputStream(); // throws!

In my case, I happen to know that the content is 404, but I'd still like to read the body of the response anyway.

(In my actual case the response code is 403, but the body of the response explains the reason for rejection, and I'd like to display that to the user.)

How can I access the response body?

Answer Source

Here is the bug report (close, will not fix, not a bug).

Their advice there is to code like this:

HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() == 200) {
    _is = httpConn.getInputStream();
} else {
     /* error from server */
    _is = httpConn.getErrorStream();