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

不问归期 提交于 2019-11-26 15:43:55

问题


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?


回答1:


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




回答2:


To make things crystal clear, here is my working code:

if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}


来源:https://stackoverflow.com/questions/25011927/how-to-get-response-body-using-httpurlconnection-when-code-other-than-2xx-is-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!