zoukankan      html  css  js  c++  java
  • 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);

     
  • 相关阅读:
    1005: [HNOI2008]明明的烦恼
    1006: [HNOI2008]神奇的国度
    1007: [HNOI2008]水平可见直线
    1011: [HNOI2008]遥远的行星
    1025: [SCOI2009]游戏
    HTTP1.0和HTTP1.1的区别
    各排序算法的时间复杂度和空间复杂度
    换钱最少货币数
    矩阵的最小路径和
    背包问题
  • 原文地址:https://www.cnblogs.com/xxyBlogs/p/5745038.html
Copyright © 2011-2022 走看看