在Java中,当HTTP结果为404范围时,此代码会抛出异常:
URL url = new URL("http://stackoverflow.com/asdf404notfound");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getInputStream(); // throws!
在我的例子中,我碰巧知道内容是404,但我仍然希望阅读响应的正文。
(在我的实际案例中,响应代码是403,但是响应的主体解释了拒绝的原因,我想将其显示给用户。)
如何访问响应体?
发布于 2009-03-05 03:26:26
Here is the bug report (关闭,不会修复,不是bug)。
他们的建议是这样编写代码:
HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
_is = httpConn.getInputStream();
} else {
/* error from server */
_is = httpConn.getErrorStream();
}
发布于 2015-06-30 02:34:01
这和我遇到的问题是一样的:如果你试图从连接中读取getInputStream()
,HttpUrlConnection
会返回FileNotFoundException
。
当状态码高于400时,您应该改用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....
通过这种方式,您将能够在成功和错误情况下获得所需的响应。
希望这能有所帮助!
发布于 2016-05-17 19:50:20
在.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();
}
https://stackoverflow.com/questions/613307
复制相似问题