首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >读取Java中的错误响应正文

读取Java中的错误响应正文
EN

Stack Overflow用户
提问于 2009-03-05 01:46:40
回答 7查看 87.8K关注 0票数 100

在Java中,当HTTP结果为404范围时,此代码会抛出异常:

代码语言:javascript
复制
URL url = new URL("http://stackoverflow.com/asdf404notfound");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getInputStream(); // throws!

在我的例子中,我碰巧知道内容是404,但我仍然希望阅读响应的正文。

(在我的实际案例中,响应代码是403,但是响应的主体解释了拒绝的原因,我想将其显示给用户。)

如何访问响应体?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2009-03-05 03:26:26

Here is the bug report (关闭,不会修复,不是bug)。

他们的建议是这样编写代码:

代码语言:javascript
复制
HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
    _is = httpConn.getInputStream();
} else {
     /* error from server */
    _is = httpConn.getErrorStream();
}
票数 182
EN

Stack Overflow用户

发布于 2015-06-30 02:34:01

这和我遇到的问题是一样的:如果你试图从连接中读取getInputStream()HttpUrlConnection会返回FileNotFoundException

当状态码高于400时,您应该改用getErrorStream()

更重要的是,请小心,因为它不仅仅是200作为成功状态码,甚至201,204等经常被用作成功状态。

下面是我如何管理它的一个示例

代码语言:javascript
复制
... connection code code code ...

// Get the response code 
int statusCode = connection.getResponseCode();

InputStream is = null;

if (statusCode >= 200 && statusCode < 400) {
   // Create an InputStream in order to extract the response object
   is = connection.getInputStream();
}
else {
   is = connection.getErrorStream();
}

... callback/response to your handler....

通过这种方式,您将能够在成功和错误情况下获得所需的响应。

希望这能有所帮助!

票数 15
EN

Stack Overflow用户

发布于 2016-05-17 19:50:20

在.Net中,您可以使用WebException的Response属性来访问异常上的流。所以我想这对Java来说是一个很好的方式。

代码语言:javascript
复制
private InputStream dispatch(HttpURLConnection http) throws Exception {
    try {
        return http.getInputStream();
    } catch(Exception ex) {
        return http.getErrorStream();
    }
}

或者是我使用的实现。(可能需要对编码或其他内容进行更改。适用于当前环境。)

代码语言:javascript
复制
private String dispatch(HttpURLConnection http) throws Exception {
    try {
        return readStream(http.getInputStream());
    } catch(Exception ex) {
        readAndThrowError(http);
        return null; // <- never gets here, previous statement throws an error
    }
}

private void readAndThrowError(HttpURLConnection http) throws Exception {
    if (http.getContentLengthLong() > 0 && http.getContentType().contains("application/json")) {
        String json = this.readStream(http.getErrorStream());
        Object oson = this.mapper.readValue(json, Object.class);
        json = this.mapper.writer().withDefaultPrettyPrinter().writeValueAsString(oson);
        throw new IllegalStateException(http.getResponseCode() + " " + http.getResponseMessage() + "\n" + json);
    } else {
        throw new IllegalStateException(http.getResponseCode() + " " + http.getResponseMessage());
    }
}

private String readStream(InputStream stream) throws Exception {
    StringBuilder builder = new StringBuilder();
    try (BufferedReader in = new BufferedReader(new InputStreamReader(stream))) {
        String line;
        while ((line = in.readLine()) != null) {
            builder.append(line); // + "\r\n"(no need, json has no line breaks!)
        }
        in.close();
    }
    System.out.println("JSON: " + builder.toString());
    return builder.toString();
}
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/613307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档