问题描述:
使用httpClient时候,出现java.io.IOException: Attempted read from closed stream.
原始代码:
public static String postJosn(String url, String jsonString) throws Exception { SSLContext sslContext = SSLContexts.custom().useTLS().build();
SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,
null);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(f).build();
// 设置请求超时时间 15秒
//client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
HttpPost myPost = new HttpPost(url);
myPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
myPost.setHeader("charset", "utf-8"); StringEntity s = new StringEntity(jsonString, "utf-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json;charset=utf-8");
myPost.addHeader("Content-Type", "application/json;charset=utf-8");
myPost.setEntity(s); HttpResponse res = client.execute(myPost);
HttpEntity entity = res.getEntity();
//myPost.releaseConnection();
log.info(EntityUtils.toString(entity, "utf-8"));;
return EntityUtils.toString(entity, "utf-8");
}
原因分析:
EntityUtils.toString(HttpEntity entity, String defaultCharset)方法中操作的是流数据,流数据是一次性数据所以同一个HttpEntity不能使用多次该方法.
源码: