Reading the body of an error response in Java

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

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

In my case, I know that the content is 404, but I would still like to read the body of the answer anyway.

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

How can I access the body of the response?

+83
Mar 05 '09 at 1:46
source share
6 answers

Here is the error report (close, not fix, not error).

Their advice is as follows:

 HttpURLConnection httpConn = (HttpURLConnection)_urlConnection; InputStream _is; if (httpConn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) { _is = httpConn.getInputStream(); } else { /* error from server */ _is = httpConn.getErrorStream(); } 
+156
Mar 05 '09 at 3:26
source share

This is the same problem as mine: HttpUrlConnection returns a FileNotFoundException if you try to read getInputStream() from the connection.
Use getErrorStream() instead if the status code is above 400.

Moreover, be careful, since not only 200 is a success status code, even 201, 204, etc. often used as success statuses.

Here is an example of how I went to manage it

 ... connection code code code ... // Get the response code int statusCode = connection.getResponseCode(); InputStream is = null; if (statusCode >= 200 && statusCode < 400) { // Create an InputStream in order to extract the response object is = connection.getInputStream(); } else { is = connection.getErrorStream(); } ... callback/response to your handler.... 

Thus, you can get the necessary answer both in case of success and in case of errors.

Hope this helps!

+13
Jun 29 '15 at 18:34
source share

In .Net, you have the Response property for WebException, which gives access to the stream as an exception. So I think this is a good way for Java, ...

 private InputStream dispatch(HttpURLConnection http) throws Exception { try { return http.getInputStream(); } catch(Exception ex) { return http.getErrorStream(); } } 

Or the implementation I used. (Perhaps you need changes to encode or other things. Works in the current environment.)

 private String dispatch(HttpURLConnection http) throws Exception { try { return readStream(http.getInputStream()); } catch(Exception ex) { readAndThrowError(http); return null; // <- never gets here, previous statement throws an error } } private void readAndThrowError(HttpURLConnection http) throws Exception { if (http.getContentLengthLong() > 0 && http.getContentType().contains("application/json")) { String json = this.readStream(http.getErrorStream()); Object oson = this.mapper.readValue(json, Object.class); json = this.mapper.writer().withDefaultPrettyPrinter().writeValueAsString(oson); throw new IllegalStateException(http.getResponseCode() + " " + http.getResponseMessage() + "\n" + json); } else { throw new IllegalStateException(http.getResponseCode() + " " + http.getResponseMessage()); } } private String readStream(InputStream stream) throws Exception { StringBuilder builder = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = in.readLine()) != null) { builder.append(line); // + "\r\n"(no need, json has no line breaks!) } in.close(); } System.out.println("JSON: " + builder.toString()); return builder.toString(); } 
+11
May 17 '16 at 11:50
source share

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

+2
Mar 05 '09 at 2:03
source share

Check the response code first, then use HttpURLConnection.getErrorStream()

+2
Mar 05 '09 at 2:20
source share
 InputStream is = null; if (httpConn.getResponseCode() !=200) { is = httpConn.getErrorStream(); } else { /* error from server */ is = httpConn.getInputStream(); } 
0
Jan 19 '10 at 10:30
source share



All Articles