Apache HttpClient - 关闭连接

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

手动关闭 HTTP 连接时,请按照以下步骤操作 −


步骤 1 - 创建一个 HttpClient 对象

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 类表示 HTTP GET 请求,该请求使用 URI 检索给定服务器的信息。

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

HttpGet httpGet = new HttpGet("http://www.w3schools.cn/");

步骤 4 - 执行Get请求

CloseableHttpClient 对象的 execute() 方法接受 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();
}

示例

每当您创建/获取对象(例如请求、响应流等)时,请在下一行中启动 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.w3schools.cn/");

         //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();
      }
   }
}

输出

在执行上述程序时,会生成以下输出 −

<!DOCTYPE html>
<!--[if IE 8]><html class = "ie ie8"> <![endif]-->
<!--[if IE 9]><html class = "ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang = "en-US"> <!--<![endif]-->
<head>
<!-- Basic -->
<meta charset = "utf-8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes">
<link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css"
rel = "stylesheet" type = "text/css" />
<link rel = "stylesheet" href = "/questions/css/home.css?v = 3" />
<script src = "/questions/js/jquery.min.js"></script>
<script src = "/questions/js/fontawesome.js"></script>
<script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script>
</head>
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . 
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-232293-17');
</script>
</body>
</html>