Apache-httpclient-closing-connection

提供:Dev Guides
移動先:案内検索

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* クラスは、URIを使用して指定されたサーバーの情報を取得するHTTP GET要求を表します。

URIを表す文字列を渡してHttpGetクラスをインスタンス化することにより、HTTP GETリクエストを作成します。

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

ステップ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.finddevguides.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>
<!--[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>