zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    react脚手架和JSX
    promise
    防抖和节流
    call/apply/bind 用法
    js this指向
    vue单页面应用刷新网页后vuex的state数据丢失的解决方案
    Echarts基础
    继承
    原型链
    vue项目中使用生成动态二维码
  • 原文地址:https://www.cnblogs.com/lilefordream/p/5211930.html
Copyright © 2011-2022 走看看