使用HttpClient出现java.io.IOException: Attempted read from closed stream

感情迁移 提交于 2020-12-16 06:20:40

问题描述:

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

源码:

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!