某些情况下,比如连接目标网页超时时,我们需要及时中断此次HTTP请求并释放相关资源,以节省时间和资源进行其他的请求。如下的例子演示了如何在正常结束前中止一个HTTP请求。
package cn.ysh.studio.crawler.httpclient;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;/** * 演示如何在正常完成之前终止一个HTTP请求 * * @author Shenghany * @date 2013-5-19 */publicclassClientAbortMethod{publicfinalstaticvoid main(String[] args)throwsException{HttpClient httpclient =newDefaultHttpClient();try{// 创建一个Get请求HttpGet httpget =newHttpGet("http://www.yshjava.cn");System.out.println("executing request "+ httpget.getURI());//执行Get请求HttpResponse response = httpclient.execute(httpget);//获取响应实体HttpEntity entity = response.getEntity();System.out.println("----------------------------------------");System.out.println(response.getStatusLine());if(entity !=null){System.out.println("Response content length: "+ entity.getContentLength());}System.out.println("----------------------------------------");// 在读取响应实体内容之前就终止此次Get请求 httpget.abort();}finally{// 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源 httpclient.getConnectionManager().shutdown();}}}