java.io.IOException: Attempted read from closed stream

代码如下,执行的时候提示“java.io.IOException: Attempted read from closed stream.”
 @Test
    public void test_temp(){
        String url="http://ssov1.59iedu.com/login?TARGET=http://med.ihbedu.com:80/gateway/web/sso/auth&js&callback=loginThen&1470491151264&nocache=1470491171451";
        this.HttpGet(url);

    }
    public void HttpGet(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();//建立httpclient
        HttpGet httpGet = new HttpGet(url);//建立httpget
        System.out.println("get请求的地址:" + httpGet.getURI());
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);//执行get请求,并结果保存
            System.out.println("get请求返回的状态码:" + response.getStatusLine().getStatusCode());
            HttpEntity httpEntity = response.getEntity();//将保存的response转为实体
            try {

                if (httpEntity != null) {
                    {
                        System.out.println("get请求返回的response值:" + EntityUtils.toString(httpEntity));
                        System.out.println("lt的值:"+EntityUtils.toString(httpEntity).split("lt:\"")[1].split("\",")[0]);
                    }
                }
            } finally {
                EntityUtils.consume(httpEntity);//关闭实体
                response.close();//关闭response
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();//关闭httpclient
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
原因是如下特别指出我的脚本中以下2个输出,这个输出中调用了2次 EntityUtils.toString(httpEntity) ,而根据httpclient的官方说明中,EntityUtils.toString(httpEntity) 这个被调用一次后就会自动销毁,而我调用了2次所有就报错了

System.out.println("get请求返回的response值:" + EntityUtils.toString(httpEntity));
System.out.println("lt的值:"+EntityUtils.toString(httpEntity).split("lt:\"")[1].split("\",")[0]);

于是把这2个输出脚本改为如下即可,只要调用一次就好

String responseStr=EntityUtils.toString(httpEntity);
System.out.println("get请求返回的response值:" + responseStr);
String str=responseStr.split("lt:\"")[1].split("\",")[0];
System.out.println("lt的值:"+str);

 

 

转载于:https://www.cnblogs.com/xxyBlogs/p/5745038.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值