zoukankan      html  css  js  c++  java
  • 使用HttpClient出现java.io.IOException: Attempted read from closed stream

    问题描述:

    使用httpClient时候,出现java.io.IOException: Attempted read from closed stream.

    原始代码:

     1     public static String postJosn(String url, String jsonString) throws Exception {
     2 
     3         SSLContext sslContext = SSLContexts.custom().useTLS().build();
     4         SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,
     5                 null);
     6         CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(f).build();
     7         // 设置请求超时时间 15秒
     8         //client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
     9         HttpPost myPost = new HttpPost(url);
    10         myPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
    11         myPost.setHeader("charset", "utf-8");
    12 
    13         StringEntity s = new StringEntity(jsonString, "utf-8");
    14         s.setContentEncoding("UTF-8");
    15         s.setContentType("application/json;charset=utf-8");
    16         myPost.addHeader("Content-Type", "application/json;charset=utf-8");
    17         myPost.setEntity(s);
    18 
    19         HttpResponse res = client.execute(myPost);
    20         HttpEntity entity = res.getEntity();
    21         //myPost.releaseConnection();
    22         log.info(EntityUtils.toString(entity, "utf-8"));;
    23         return EntityUtils.toString(entity, "utf-8");
    24     }

    原因分析:

    EntityUtils.toString(HttpEntity entity, String defaultCharset)方法中操作的是流数据,流数据是一次性数据所以同一个HttpEntity不能使用多次该方法.

    源码:

  • 相关阅读:
    H5版俄罗斯方块(5)---需求演进和产品迭代
    vim 常用 NERDTree 快捷键
    C和C++中include 搜索路径的一般形式以及gcc搜索头文件的路径
    MySQL复制协议
    深入解析MySQL replication协议
    Install CodeBlocks in CentOS 7
    Impala 源码分析-FE
    Elasticsearch 6.x 的分页查询数据
    1、树莓派3B开箱+安装系统
    Python创建ES索引
  • 原文地址:https://www.cnblogs.com/cocoxu1992/p/10485882.html
Copyright © 2011-2022 走看看