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