NoToast
NoToast

Reputation: 98

How do I read a HTTP response if the server returned a 502 error?

I used URLConnection to send a POST request to a server and I am using the following code to read the response:

String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));   
while ((line = reader.readLine()) != null) {
    response += line;
}
reader.close();

However, the server will sometimes return a 502 error with a meaningful error message in the response, which I would like to obtain. My problem is that attempting to create the BufferedReader in that case will result in a java.io.IOException:

Server returned HTTP response code: 502 for URL: <url>

How can I bypass this?

Upvotes: 0

Views: 3201

Answers (1)

mistahenry
mistahenry

Reputation: 8744

Modify your code along these lines so that you can get the errorstream rather than throw the IOException

HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
    is = httpConn.getErrorStream();
} else {
    is = httpConn.getInputStream();
}

BufferedReader reader = new BufferedReader(new  InputStreamReader(is));   
while ((line = reader.readLine()) != null) {
     response += line;
}
reader.close();

Upvotes: 3

Related Questions