Apache-httpclient-response-handlers

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

Apache HttpClient-応答ハンドラー

応答ハンドラーを使用してHTTP応答を処理することをお勧めします。 この章では、応答ハンドラーの作成方法と、応答ハンドラーを使用して応答を処理する方法について説明します。

応答ハンドラーを使用すると、すべてのHTTP接続が自動的に解放されます。

応答ハンドラーを作成する

HttpClient APIは、パッケージ* org.apache.http.client。に *ResponseHandler と呼ばれるインターフェイスを提供します。応答ハンドラを作成するには、このインターフェイスを実装し、* handleResponse()*メソッドをオーバーライドします。

すべての応答にはステータスコードがあり、ステータスコードが200〜300の場合、アクションが正常に受信され、理解され、受け入れられたことを意味します。 したがって、この例では、このようなステータスコードを持つ応答のエンティティを処理します。

応答ハンドラーを使用して要求を実行する

以下の手順に従って、応答ハンドラーを使用して要求を実行します。

ステップ1-HttpClientオブジェクトを作成する

*HttpClients* クラスの* createDefault()*メソッドは、 *HttpClient* インターフェイスの基本実装である *CloseableHttpClient* クラスのオブジェクトを返します。 このメソッドを使用して、HttpClientオブジェクトを作成します
CloseableHttpClient httpclient = HttpClients.createDefault();

ステップ2-応答ハンドラーのインスタンス化

次のコード行を使用して、上記で作成した応答ハンドラーオブジェクトをインスタンス化します-

ResponseHandler<String> responseHandler = new MyResponseHandler();

ステップ3-HttpGetオブジェクトを作成する

*HttpGet* クラスは、URIを使用して指定されたサーバーの情報を取得するHTTP GET要求を表します。

HttpGetクラスをインスタンス化し、URIを表す文字列をコンストラクターのパラメーターとして渡すことにより、HttpGet要求を作成します。

ResponseHandler<String> responseHandler = new MyResponseHandler();

ステップ4-応答ハンドラーを使用してGetリクエストを実行する

*CloseableHttpClient* クラスには、* execute()*メソッドのバリアントがあり、2つのオブジェクト *ResponseHandler* およびHttpUriRequestを受け入れ、応答オブジェクトを返します。
String httpResponse = httpclient.execute(httpget, responseHandler);

次の例は、応答ハンドラーの使用方法を示しています。

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

class MyResponseHandler implements ResponseHandler<String>{

   public String handleResponse(final HttpResponse response) throws IOException{

     //Get the status of the response
      int status = response.getStatusLine().getStatusCode();
      if (status >= 200 && status < 300) {
         HttpEntity entity = response.getEntity();
         if(entity == null) {
            return "";
         } else {
            return EntityUtils.toString(entity);
         }

      } else {
         return ""+status;
      }
   }
}

public class ResponseHandlerExample {

   public static void main(String args[]) throws Exception{

     //Create an HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

     //instantiate the response handler
      ResponseHandler<String> responseHandler = new MyResponseHandler();

     //Create an HttpGet object
      HttpGet httpget = new HttpGet("http://www.finddevguides.com/");

     //Execute the Get request by passing the response handler object and HttpGet object
      String httpresponse = httpclient.execute(httpget, responseHandler);

      System.out.println(httpresponse);
   }
}

出力

上記のプログラムは、次の出力を生成します-

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