当服务器返回错误时,我在检索Json响应方面存在问题。请参见下面的详细信息。
如何执行请求
我使用 java.net.HttpURLConnection
。 我设置请求属性,然后执行以下操作:
conn = (HttpURLConnection) url.openConnection();
之后,当请求成功时,我会收到响应的 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异常:
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
// throws java.io.IOException: Server returned HTTP response code: 401 for URL: www.example.com
服务器肯定会发送正文内容,我在外部工具Burp Suite中已经看到了。HTTP/1.1 401 Unauthorized
{"type":"AuthApiException","message":"AuthApiException","errors":[{"field":"email","message":"Invalid username and/or password."}]}
我可以使用以下方法获取响应消息(例如,“Internal Server Error”)和代码(例如,“500”):
conn.getResponseMessage();
conn.getResponseCode();
但是我无法获取请求正文...也许在库中有一些我没有注意到的方法吗?