Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I get response body in HttpURLConnection?

The getResponseMessage is a method of Java HttpURLConnection class. This method is used to get response code from HTTP response message. For example, if the response code from a server is HTTP/1.0 200 OK or HTTP/1.0 404 Not Found, it extracts the string OK and Not Found else returns null if HTTP is not valid.

Which method of HttpURLConnection class is used to retrieve the response status from server?

Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc. We can call getResponseCode() to get the response HTTP code.

How do I get HttpURLConnection error message?

Java HttpURLConnection getErrorStream() Method The getErrorStream() is the method of HttpURLConnection class. This method is used to get an error stream if the connection is disconnected. This method does not set the connection.


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


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()));
}

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);
        }
}