问题描述:
使用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不能使用多次该方法.
源码:
来源:oschina
链接:https://my.oschina.net/u/4386639/blog/3623943