java.io.IOException: Attempted read from closed stream
前言:
代码如下,执行的时候提示“java.io.IOException: Attempted read from closed stream.”
public static JSONObject post(String url,StringBuffer params,String token ){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url + "?" + params);
httpPost.setHeader("Content-Type", "application/json, text/plain, */*");
httpPost.setHeader("Authorization",token);
// 响应模型
CloseableHttpResponse response = null;
try {
// send the Post Request
response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
String jsonString = EntityUtils.toString(responseEntity);
resBody = JSONObject.fromObject(jsonString);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//release resource
release(httpClient,response);
}
return resBody;
}
原因
response.getEntity()所得到的流是不可重复读取的,所得的实体只能读取一次,读取一次后,流就关闭了。EntityUtils.toString(responseEntity)被调用一次后就会自动销毁,而我调用了2次,所以就报错了。
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
String jsonString = EntityUtils.toString(responseEntity);
解决方法
把这2个输出脚本改为如下即可,只要调用一次就好:
String jsonString = EntityUtils.toString(responseEntity);
System.out.println("响应内容为:" + jsonString);