当返回2xx以外的代码时,如何使用HttpURLConnection获取响应体?

时间:2014-07-29 09:20:03

标签: java http httpurlconnection

如果服务器返回错误,我在检索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();

但我无法检索请求正文...也许我在库中没有注意到某种方法?

3 个答案:

答案 0 :(得分:113)

如果回复代码不是200或2xx,请使用getErrorStream()代替getInputStream().

答案 1 :(得分:52)

为了使事情变得清晰,这是我的工作代码:

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

答案 2 :(得分:3)

这是一种从服务器获得成功响应的简单方法,例如PHP echo,否则会显示错误消息。

BufferedReader br = null;
if (conn.getResponseCode() == 200) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
}