100

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

URL url = new URL("http://stackoverflow.com/asdf404notfound");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getInputStream(); // throws!

就我而言,我碰巧知道内容是 404,但我仍然想阅读响应的正文。

(在我的实际情况下,响应代码是 403,但响应的正文解释了拒绝的原因,我想向用户显示。)

如何访问响应正文?

4

8 回答 8

182

这是错误报告(关闭,不会修复,不是错误)。

他们的建议是这样编码:

HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
    _is = httpConn.getInputStream();
} else {
     /* error from server */
    _is = httpConn.getErrorStream();
}
于 2009-03-05T03:26:26.427 回答
15

这与我遇到的问题相同: 如果您尝试从连接中读取,HttpUrlConnection则会返回。 您应该在状态码高于 400 时使用。FileNotFoundExceptiongetInputStream()
getErrorStream()

不仅如此,请注意,因为成功状态码不仅是200,甚至201、204等也经常被用作成功状态。

这是我如何管理它的示例

... 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....

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

希望这可以帮助!

于 2015-06-29T18:34:01.333 回答
14

在 .Net 中,您拥有 WebException 的 Response 属性,该属性可以在异常情况下访问流。所以我想这对Java来说是一个好方法,......

private InputStream dispatch(HttpURLConnection http) throws Exception {
    try {
        return http.getInputStream();
    } catch(Exception ex) {
        return http.getErrorStream();
    }
}

或者我使用的一个实现。(可能需要更改编码或其他内容。在当前环境中工作。)

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();
}
于 2016-05-17T11:50:20.237 回答
2

我知道这并不能直接回答这个问题,但是您可能不想使用 Sun 提供的 HTTP 连接库,而是想看看Commons HttpClient,它(在我看来)有一个更容易使用的 API。

于 2009-03-05T02:03:24.300 回答
2

首先检查响应代码,然后使用HttpURLConnection.getErrorStream()

于 2009-03-05T02:20:51.170 回答
1
InputStream is = null;
if (httpConn.getResponseCode() !=200) {
    is = httpConn.getErrorStream();
} else {
     /* error from server */
    is = httpConn.getInputStream();
}
于 2010-01-19T10:30:00.073 回答
1

我的运行代码。

  HttpURLConnection httpConn = (HttpURLConnection) urlConn;    
 if (httpConn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                        in = new InputStreamReader(urlConn.getInputStream());
                        BufferedReader bufferedReader = new BufferedReader(in);
                        if (bufferedReader != null) {
                            int cp;
                            while ((cp = bufferedReader.read()) != -1) {
                                sb.append((char) cp);
                            }
                            bufferedReader.close();
                        }
                            in.close();

                    } else {
                        /* error from server */
                        in = new InputStreamReader(httpConn.getErrorStream());
                    BufferedReader bufferedReader = new BufferedReader(in);
                    if (bufferedReader != null) {
                        int cp;
                        while ((cp = bufferedReader.read()) != -1) {
                            sb.append((char) cp);
                        }
                        bufferedReader.close();
                    }    
                    in.close();
                    }
                    System.out.println("sb="+sb);
于 2019-09-22T08:32:15.690 回答
0

如何在 java 中读取 404 响应正文:

使用 Apache 库 - https://hc.apache.org/httpcomponents-client-4.5.x/httpclient/apidocs/

或 Java 11 - https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html

下面给出的片段使用 Apache:

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse resp = client.execute(new HttpGet(domainName + "/blablablabla.html"));
String response = EntityUtils.toString(resp.getEntity());
于 2020-03-19T11:07:56.453 回答