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

因而把這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);web

相關文章
相關標籤/搜索