📅  最后修改于: 2020-11-18 08:27:52             🧑  作者: Mango
如果要手动处理HTTP响应而不是使用响应处理程序,则需要自己关闭所有http连接。本章介绍如何手动关闭连接。
在手动关闭HTTP连接时,请遵循以下步骤-
HttpClients类的createDefault()方法返回CloseableHttpClient类的对象,该对象是HttpClient接口的基本实现。
使用此方法,创建一个HttpClient对象,如下所示-
CloseableHttpClient httpClient = HttpClients.createDefault();
启动一个try-finally块,在try块中的程序中写入剩余的代码,然后在finally块中关闭CloseableHttpClient对象。
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
//Remaining code . . . . . . . . . . . . . . .
}finally{
httpClient.close();
}
HttpGet类表示HTTP GET请求,该请求使用URI检索给定服务器的信息。
通过传递表示URI的字符串实例化HttpGet类来创建HTTP GET请求。
HttpGet httpGet = new HttpGet("http://www.tutorialspoint.com/");
CloseableHttpClient对象的execute()方法接受HttpUriRequest (接口)对象(即HttpGet,HttpPost,HttpPut,HttpHead等),并返回响应对象。
使用给定的方法执行请求-
HttpResponse httpResponse = httpclient.execute(httpGet);
启动另一个try-finally块(嵌套在先前的try-finally中),在此try块中的程序中写入剩余的代码,并在finally块中关闭HttpResponse对象。
CloseableHttpClient httpclient = HttpClients.createDefault();
try{
. . . . . . .
. . . . . . .
CloseableHttpResponse httpresponse = httpclient.execute(httpget);
try{
. . . . . . .
. . . . . . .
}finally{
httpresponse.close();
}
}finally{
httpclient.close();
}
每当创建/获取对象(例如请求,响应流等)时,在下一行中启动try 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.tutorialspoint.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();
}
}
}
执行上述程序时,将生成以下输出-
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .