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);

转载于:https://www.cnblogs.com/fstimers/p/10739353.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值