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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM