如果手动处理HTTP响应而不是使用响应处理程序,则需要自己关闭所有http连接。本章介绍如何手动关闭连接。
手动关闭HTTP连接时,请按照以下步骤操作 -
第1步 - 创建一个HttpClient对象
HttpClients类的createDefault()
方法返回CloseableHttpClient
类的对象,该对象是HttpClient
接口的基本实现。
使用此方法,创建一个HttpClient
对象,如下所示 -
CloseableHttpClient httpClient = HttpClients.createDefault();
Java
第2步 - try-finally块
开始try-finally
块,在try
块中的程序中写入剩余的代码,并在finally
块中关闭CloseableHttpClient
对象。
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
//Remaining code . . . . . . . . . . . . . . .
}finally{
httpClient.close();
}
Java
第3步 - 创建一个HttpGetobject
HttpGet
类表示HTTP GET请求,该请求使用URI检索给定服务器的信息。通过传递表示URI的字符串来实例化HttpGet
类来创建HTTP GET请求。
HttpGet httpGet = new HttpGet("http://www.kaops.com/");
Java
第4步 - 执行Get请求CloseableHttpClient
对象的execute()
方法接受HttpUriRequest(接口)对象(即:HttpGet
,HttpPost
,HttpPut
,HttpHead
等)并返回响应对象。
使用给定方法执行请求 -
HttpResponse httpResponse = httpclient.execute(httpGet);
Java
第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();
}
Java
示例
每当创建/获取请求,响应流等对象时,在下一行中启动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.kaops.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();
}
}
}
Java
执行上面示例代码,得到以下结果:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>考评师 - 一个专注于面试题和知识测评的网站</title>
<meta name="baidu-site-verification" content="SMo5w14fvk" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="keywords" content="考试,面试,面试题,考试题">
<meta name="description" content="考评师网是一个专注于提供知识考评测试和面试题的网站。汇集了各个行业,各种技术,知识等面试题和知识测试。">
<link rel="stylesheet" href="/static/layui/css/layui.css">
<link rel="stylesheet" href="/static/css/global.css">
</head>
<body>
... ...