开发手册 欢迎您!
软件开发者资料库

Apache HttpClient - 关闭连接

Apache HttpClient关闭连接 - 从简单和简单的步骤学习Apache HttpClient,从基本到高级概念,包括概述,环境设置,Http获取请求,Http Post请求,响应处理程序,关闭连接,中止请求,拦截器,用户身份验证,使用代理,代理身份验证,基于表单的登录,Cookie管理,多线程,自定义SSL上下文,分段上传。

如果您手动处理HTTP响应而不是使用响应处理程序,则需要自己关闭所有http连接.本章介绍如何手动关闭连接.

手动关闭HTTP连接时,请按照下面给出的步骤&减去;

步骤1  - 创建HttpClient object

HttpClients 类的 createDefault()方法返回类 CloseableHttpClient 的对象,这是HttpClient接口的基本实现.

使用此方法,创建一个 HttpClient 对象,如下所示 :

CloseableHttpClient httpClient = HttpClients.createDefault();

步骤2  - 启动try-finally块

启动try-finally块,写下剩下的代码try块中的程序并关闭finally块中的CloseableHttpClient对象.

CloseableHttpClient httpClient = HttpClients.createDefault();try{   //Remaining code . . . . . . . . . . . . . . .}finally{   httpClient.close(); }

第3步 - 创建HttpGetobject

HttpGet 类表示使用URI检索给定服务器信息的HTTP GET请求.

通过传递表示URI的字符串来实例化HttpGet类来创建HTTP GET请求.

HttpGet httpGet = new HttpGet("http://www.IT屋.com/");

步骤4  - 执行获取请求

执行()方法 CloseableHttpClient 对象接受 HttpUriRequest (接口)对象(即HttpGet,HttpPost,HttpPut,HttpHead等)并返回响应对象.

使用给定方法执行请求 :

HttpResponse httpResponse = httpclient.execute(httpGet);

步骤5  - 启动另一个(嵌套)try-finally

启动另一个try-finally块(嵌套在先前的try-finally),在这个try块的程序中写下剩下的代码并关闭finally块中的HttpResponse对象.

CloseableHttpClient httpclient = HttpClients.createDefault();try{   . . . . . . .   . . . . . . .   CloseableHttpResponse httpresponse = httpclient.execute(httpget);   try{      . . . . . . .      . . . . . . .   }finally{      httpresponse.close();   }}finally{   httpclient.close();}

示例

每当您创建/获取请求,响应流等对象时,在下一行开始尝试finally块,在try中写下剩余的代码并关闭finally块中的相应对象,如以下程序中所示 :

import java.util.Scanner;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;public class CloseConnectionExample {      public static void main(String args[])throws Exception{       //Create an HttpClient object      CloseableHttpClient httpclient = HttpClients.createDefault();      try{         //Create an HttpGet object         HttpGet httpget = new HttpGet("http://www.IT屋.com/");         //Execute the Get request         CloseableHttpResponse httpresponse = httpclient.execute(httpget);         try{            Scanner sc = new Scanner(httpresponse.getEntity().getContent());            while(sc.hasNext()) {               System.out.println(sc.nextLine());            }         }finally{            httpresponse.close();         }      }finally{         httpclient.close();      }   } }

输出

执行上述程序时,生成以下输出 :

 . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . .