org.apache.http.HttpResponse 获取entry Attempted read from closed stream
时间: 2023-11-30 19:05:08 浏览: 177
http发送请求获取返回结果
当使用`org.apache.http.HttpResponse`对象的`getEntity().getContent()`方法获取返回的响应内容时,如果该响应内容的流已经被关闭,再次尝试读取流中的数据就会抛出"Attempted read from closed stream"异常。
解决这个问题的方法是,在读取完响应内容后,手动关闭响应内容的流。代码示例:
```
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
try {
// 读取流中的数据
} finally {
inputStream.close();
}
```
这样,在`finally`块中关闭流,即使在读取过程中抛出了异常,也能保证流被正确关闭,避免了"Attempted read from closed stream"异常的发生。
阅读全文