tags:

views:

609

answers:

4

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?

+2  A: 

I know that this doesn't answer the question directly, but instead of using the HTTP connection library provided by Sun, you might want to take a look at Commons HttpClient, which (in my opinion) has a far easier API to work with.

matt b
A: 

First check the response code and then use HttpURLConnection.getErrorStream()

Chris Dolan
+3  A: 

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

There advice there is to code like this:

HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() >= 400) {
    _is = httpConn.getInputStream();
} else {
     /* error from server */
    _is = httpConn.getErrorStream();
}
TofuBeer
Does indeed seem "as expected" given the API design, sounds reasonable to me
matt b
Wouldn't you want to get the error stream when the response code is >= 400, rather than the other way around?
Stephen Swensen
@Stephen yeah, I assume so, but I just grabbed the code at the link...
TofuBeer
A: 
InputStream is = null;
if (httpConn.getResponseCode() !=200) {
    is = httpConn.getErrorStream();
} else {
     /* error from server */
    is = httpConn.getInputStream();
}