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.kaops.com/");

第4步 - 執行Get請求
CloseableHttpClient物件的execute()方法接受HttpUriRequest(介面)物件(即:HttpGetHttpPostHttpPutHttpHead等)並返回響應物件。

使用給定方法執行請求 -

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

執行上面範例程式碼,得到以下結果:

<!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>
... ...