Reputation: 98
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
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