首页 > 编程语言 > 详细

java.io.IOException: Attempted read from closed stream

时间:2016-08-06 23:30:17      阅读:376      评论:0      收藏:0      [点我收藏+]
代码如下,执行的时候提示“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);

 

 

java.io.IOException: Attempted read from closed stream

原文:http://www.cnblogs.com/xxyBlogs/p/5745038.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!