[java] How to get response body using HttpURLConnection, when code other than 2xx is returned?

I have problem with retrieving Json response in case when server returns error. See details below.

How I perform the request

I use java.net.HttpURLConnection. I setup request properties, then I do:

conn = (HttpURLConnection) url.openConnection();

After that, when request is successful, I get response Json:

br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
  sb.append(output);
}
return sb.toString();

... and the problem is:

I can't retrieve Json received when the server returns some error like 50x or 40x,. Following line throws IOException:

br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
// throws java.io.IOException: Server returned HTTP response code: 401 for URL: www.example.com

The server sends body for sure, I see it in external tool Burp Suite:

HTTP/1.1 401 Unauthorized

{"type":"AuthApiException","message":"AuthApiException","errors":[{"field":"email","message":"Invalid username and/or password."}]}

I can get response message (i.e. "Internal Server Error") and code (i.e. "500") using following methods:

conn.getResponseMessage();
conn.getResponseCode();

But I can't retrieve request body... maybe there is some method I didn't notice in the library?

This question is related to java http httpurlconnection

The answer is


Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().


This is an easy way to get a successful response from the server like PHP echo otherwise an error message.

BufferedReader br = null;
if (conn.getResponseCode() == 200) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to httpurlconnection

How to get response body using HttpURLConnection, when code other than 2xx is returned? android download pdf from url then open it with a pdf reader POST request send json data java HttpUrlConnection "PKIX path building failed" and "unable to find valid certification path to requested target" Java simple code: java.net.SocketException: Unexpected end of file from server Getting java.net.SocketTimeoutException: Connection timed out in android How to send Request payload to REST API in java? Sending a JSON HTTP POST request from Android Sending files using POST with HttpURLConnection Parse JSON from HttpURLConnection object