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不能使用多次该方法.

    源码:

  • 相关阅读:
    jQuery中$.proxy()的原理和使用
    JS中各种宽度、高度、位置、距离总结
    js中得call()方法和apply()方法的用法
    google浏览器翻译失败解决方案
    js区分移动设备与PC
    知识积累
    Django
    leetcode 27.Remove Element
    leetcode 28. Implement strStr()
    21. Merge Two Sorted Lists
  • 原文地址:https://www.cnblogs.com/cocoxu1992/p/10485882.html
Copyright © 2011-2022 走看看