【发布时间】:2014-09-20 15:00:36
【问题描述】:
如果服务器返回错误,我在检索 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."}]}
我可以使用以下方法获得响应消息(即“内部服务器错误”)和代码(即“500”):
conn.getResponseMessage();
conn.getResponseCode();
但我无法检索请求正文...也许库中有一些我没有注意到的方法?
【问题讨论】:
标签: java http httpurlconnection