httpClient 发送请求后解析流重用的问题(HttpEntity的重用:BufferedHttpEntity)

使用场景: 项目中使用httpClient发送一次http请求,以流的方式处理返回结果,开始发现返回的流只能使用一次,再次使用就会出错,后来看了一些解决方案,EntityUtils.consume(resEntity);方法直接关闭了inputStream导致流无法再次使用,后来研究发现http提供了解析流重用的方法new BufferedHttpEntity(entity)

这样可以多次使用流

项目代码如下

/**
* 发送get请求下载文件,以字节流的方式写入到本地
* @param url 服务器端下载文件的地址
* @param savePath 本地保存文件的路径
* @return
*/
private String DownLoadFile(String url, String savePath) {
String result = SystemConfig.getMsg("downloadSuccess");
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpgets = new HttpGet(url);
HttpResponse response = httpclient.execute(httpgets);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity = new BufferedHttpEntity(entity);//entity实体流保存缓冲区,否则只能操作一次流就会关闭 ,这种可以多次读取流.
//InputStream instreams = entity.getContent();
boolean DownLoadresult = downLoadResult(entity.getContent());
if(DownLoadresult){
saveFileFromStream(savePath, entity.getContent());
}else{
result = SystemConfig.getMsg("downLoadError");
}
httpgets.abort();
}else{
result = SystemConfig.getMsg("downLoadError");
}
} catch (Exception e) {
logger.error("DownLoadFile下载方法出错",e);
result = SystemConfig.getMsg("downLoadError");
}
return result;
}

原文地址:https://www.cnblogs.com/lilefordream/p/5211930.html