When I look at SO the typical answer to my question is this:
HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() == 200) {
_is = httpConn.getInputStream();
} else {
/* error from server */
_is = httpConn.getErrorStream();
}
From Read error response body in Java
This seems quite reasonable, however when I look at the implementation of HttpURLConnection.getResponseCode()
the very first thing it does is call getInputStream()
. According to the documentation getInputStream()
is supposed to throw an IOException if there was an error, hence the solution above will always throw an exception if the response code is not in the 200 range!
Have I missed something here? How am I supposed to get the response code if there is an error, if the very function that gives me the response code will throw in that case?
Here is what getResponseCode()
in java.net.HttpURLConnection.java looks like for me:
public int getResponseCode() throws IOException {
// Call getInputStream() first since getHeaderField() doesn't return
// exceptions
getInputStream();
String response = getHeaderField(0);
if (response == null) {
return -1;
}
response = response.trim();
int mark = response.indexOf(" ") + 1;
if (mark == 0) {
return -1;
}
int last = mark + 3;
if (last > response.length()) {
last = response.length();
}
responseCode = Integer.parseInt(response.substring(mark, last));
if (last + 1 <= response.length()) {
responseMessage = response.substring(last + 1);
}
return responseCode;
}