问题描述
我在检索 Json 响应时遇到问题,以防服务器返回错误.请参阅下面的详细信息.
I have problem with retrieving Json response in case when server returns error. See details below.
我使用 java.net.HttpURLConnection
.我设置请求属性,然后我做:
I use java.net.HttpURLConnection
. I setup request properties, then I do:
conn = (HttpURLConnection) url.openConnection();
之后,当请求成功时,我得到响应 Json:
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();
...问题是:
当服务器返回诸如 50x 或 40x 之类的错误时,我无法检索收到的 Json.以下行抛出 IOException:
... 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
服务器肯定会发送正文,我在外部工具 Burp Suite 中看到它:
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."}]}
我可以使用以下方法获取响应消息(即内部服务器错误")和代码(即500"):
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?
推荐答案
错误的方法被用于错误,这里是工作代码:
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()));
}
这篇关于返回 2xx 以外的代码时,如何使用 HttpURLConnection 获取响应正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!