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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25011927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:26:30  来源:igfitidea点击:

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

javahttphttpurlconnection

提问by kiedysktos

I have problem with retrieving Json response in case when server returns error. See details below.

我在检索 Json 响应时遇到问题,以防服务器返回错误。请参阅下面的详细信息。

How I perform the request

我如何执行请求

I use java.net.HttpURLConnection. I setup request properties, then I do:

我用java.net.HttpURLConnection. 我设置请求属性,然后我做:

conn = (HttpURLConnection) url.openConnection();

After that, when request is successful, I get response Json:

之后,当请求成功时,我得到响应 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:

当服务器返回诸如 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

The server sends body for sure, I see it in external tool Burp Suite:

服务器肯定会发送正文,我在外部工具 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:

我可以使用以下方法获取响应消息(即“内部服务器错误”)和代码(即“500”):

conn.getResponseMessage();
conn.getResponseCode();

But I can't retrieve request body... maybe there is some method I didn't notice in the library?

但是我无法检索请求正文......也许图书馆中有一些我没有注意到的方法?

采纳答案by user207421

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

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

回答by kiedysktos

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()));
}

回答by Sharhabeel Hamdan

This is an easy way to get a successful response from the server like PHP echo otherwise an error message.

这是一种从服务器获得成功响应的简单方法,例如 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);
        }
}