Apache-httpclient-quick-guide

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

Apache HttpClient-概要

ハイパーテキスト転送プロトコル(HTTP)は、分散型の協調型ハイパーメディア情報システム用のアプリケーションレベルのプロトコルです。 これは、1990年以降のWorld Wide Web(つまり、インターネット)のデータ通信の基盤です。 HTTPは、リクエストメソッド、エラーコード、およびヘッダーの拡張機能を使用するだけでなく、他の目的にも使用できる汎用のステートレスプロトコルです。

基本的に、HTTPはTCP/IPベースの通信プロトコルであり、World Wide Web上でデータ(HTMLファイル、画像ファイル、クエリ結果など)を配信するために使用されます。 デフォルトのポートはTCP 80ですが、他のポートも使用できます。 コンピューターが相互に通信するための標準化された方法を提供します。 HTTP仕様は、クライアントの要求データを構築してサーバーに送信する方法、およびサーバーがこれらの要求に応答する方法を定義します。

Httpクライアントとは

HTTPクライアントは転送ライブラリであり、クライアント側に常駐し、HTTPメッセージを送受信します。 最新のHTTP標準を満たす最新の機能豊富で効率的な実装を提供します。

これに加えて、クライアントライブラリを使用して、Webブラウザ、WebサービスクライアントなどのHTTPベースのアプリケーションを構築できます。

Httpクライアントの機能

以下は、HTTPクライアントの顕著な特徴です-

  • HttpClientライブラリは、使用可能なすべてのHTTPメソッドを実装します。
  • HttpClientライブラリは、Secure Socket Layerプロトコルを使用してリクエストを保護するAPIを提供します。
  • HttpClientを使用すると、プロキシを使用して接続を確立できます。
  • Basic、Digest、NTLMv1、NTLMv2、NTLM2 Sessionなどの認証スキームを使用して接続を認証できます。 HttpClientライブラリは、複数のスレッドを介した要求の送信をサポートしています。 ClientConnectionPoolManager *を使用して、さまざまなスレッドから確立された複数の接続を管理します。
  • Apache HttpClientライブラリを使用して、接続タイムアウトを設定できます。

Apache HttpClient-環境のセットアップ

この章では、Eclipse IDEでHttpClientの環境を設定する方法について説明します。 インストールを続行する前に、システムにEclipseがインストールされていることを確認してください。 そうでない場合は、Eclipseをダウンロードしてインストールします。

Eclipseの詳細については、リンク:/eclipse/index [Eclipse Tutorial]を参照してください。

ステップ1-依存関係JARファイルをダウンロードする

HttpClient(コンポーネント)Webサイトの公式https://hc.apache.org/downloads.cgi[homepage]を開き、ダウンロードページに移動します。

HttpComponentsダウンロード

次に、 _ HttpClient_ の最新の安定バージョンをダウンロードします。 ここでは、チュートリアル全体を通してバージョン4.5.6を使用しているため、 4.5.6.zip ファイルをダウンロードします。

ダウンロードしたフォルダー内に、 lib という名前のフォルダーがあります。これには、HttpClientで作業するためにプロジェクトのクラスパスに追加される必要なJarファイルが含まれています。

ステップ2-プロジェクトを作成し、ビルドパスを設定する

Eclipseを開き、サンプルプロジェクトを作成します。 プロジェクトを右クリックし、以下に示すように、 Build Path→Configure Build Path オプションを選択します。

ビルドパス

*Libraries* タブの *Java Build Path* フレームで、 *Add External JARs* をクリックします。

外部ジャーの追加

そして、libフォルダー内のすべてのjarファイルを選択し、「適用して閉じる」をクリックします。

ジャーファイル

EclipseでHttpClientライブラリを使用するよう設定されています。

Apache HttpClient-Http Getリクエスト

GETメソッドは、特定のURIを使用して特定のサーバーから情報を取得するために使用されます。 GETを使用するリクエストは、データを取得するだけで、データに他の影響を与えません。

HttpClient APIは、getリクエストメソッドを表す HttpGet という名前のクラスを提供します。

以下の手順に従って、HttpClientライブラリを使用してgetリクエストを送信します

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

*HttpClients* クラスの* createDefault()*メソッドは *CloseableHttpClient* オブジェクトを返します。これは *HttpClient* インターフェイスの基本実装です。

このメソッドを使用して、以下に示すようにHttpClientオブジェクトを作成します-

CloseableHttpClient httpclient = HttpClients.createDefault();

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

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

このクラスをインスタンス化して、HTTP GETリクエストを作成します。 このクラスのコンストラクターは、URIを表すString値を受け入れます。

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

ステップ3-Getリクエストを実行する

*CloseableHttpClient* クラスの* execute()*メソッドは、HttpUriRequest(インターフェイス)オブジェクト(つまり、 HttpGet、HttpPost、HttpPut、HttpHeadなど)と応答オブジェクトを返します。

以下に示すように、このメソッドを使用してリクエストを実行します-

HttpResponse httpresponse = httpclient.execute(httpget);

以下は、HttpClientライブラリを使用したHTTP GET要求の実行を示す例です。

import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpGetExample {

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

     //Creating a HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

     //Creating a HttpGet object
      HttpGet httpget = new HttpGet("https://www.finddevguides.com/");

     //Printing the method used
      System.out.println("Request Type: "+httpget.getMethod());

     //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

      Scanner sc = new Scanner(httpresponse.getEntity().getContent());

     //Printing the status line
      System.out.println(httpresponse.getStatusLine());
      while(sc.hasNext()) {
         System.out.println(sc.nextLine());
      }
   }
}

出力

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

Request Type: GET
<!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">
<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java
i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,
LOLCODE, Current Affairs 2018, Apache Commons Collections</title>
<meta name = "Description" content = "Parallax Scrolling, Java Cryptography, YAML,
Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common
CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache
Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC),
Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow"/>
<meta name = "Keywords" content = "Python Data Science, Java i18n, GitLab,
TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson,
TestLink, Inter Process Communication (IPC), Logo"/>
<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>
</body>
</html>

Apache HttpClient-Http Postリクエスト

POST要求は、サーバーにデータを送信するために使用されます。たとえば、HTMLフォームを使用した顧客情報、ファイルのアップロードなど。

HttpClient APIは、POST要求を表す HttpPost という名前のクラスを提供します。

HttpClientライブラリを使用してHTTP POSTリクエストを送信するには、以下の手順に従います。

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

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

このメソッドを使用して、HttpClientオブジェクトを作成します。

CloseableHttpClient httpClient = HttpClients.createDefault();

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

*HttpPost* クラスは *HTTP POST* リクエストを表します。 これにより、必要なデータが送信され、URIを使用して指定されたサーバーの情報が取得されます。
*HttpPost* クラスをインスタンス化してこのリクエストを作成し、URIを表す文字列値をコンストラクターのパラメーターとして渡します。
HttpGet httpGet = new HttpGet("http://www.finddevguides.com/");

ステップ3-Getリクエストを実行する

CloseableHttpClientオブジェクトの* execute()*メソッドは、HttpUriRequest(インターフェイス)オブジェクト(つまり、 HttpGet、HttpPost、HttpPut、HttpHeadなど)と応答オブジェクトを返します。

HttpResponse httpResponse = httpclient.execute(httpget);

以下は、HttpClientライブラリを使用したHTTP POST要求の実行を示す例です。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpPostExample {

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

     //Creating a HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

     //Creating a HttpGet object
      HttpPost httppost = new HttpPost("https://www.finddevguides.com/");

     //Printing the method used
      System.out.println("Request Type: "+httppost.getMethod());

     //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httppost);

      Scanner sc = new Scanner(httpresponse.getEntity().getContent());

     //Printing the status line
      System.out.println(httpresponse.getStatusLine());
      while(sc.hasNext()) {
         System.out.println(sc.nextLine());
      }
   }
}

出力

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

Request Type: POST
<!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">
<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java
i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,
LOLCODE, Current Affairs 2018, Apache Commons Collections</title>
<meta name = "Description" content = "Parallax Scrolling, Java Cryptography, YAML,
Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common
CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache
Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC),
Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow"/>
<meta name = "Keywords" content="Python Data Science, Java i18n, GitLab,
TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson,
TestLink, Inter Process Communication (IPC), Logo"/>
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" conten t= "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>
</body>
</html>

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>

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>

Apache HttpClient-リクエストの中止

  • abort()*メソッドを使用して現在のHTTPリクエストを中止できます。つまり、特定のリクエストでこのメソッドを呼び出した後、その実行は中止されます。

このメソッドが1回の実行後に呼び出された場合、その実行の応答は影響を受けず、後続の実行は中止されます。

次の例を見ると、HttpGetリクエストが作成され、* getMethod()*を使用してリクエスト形式が出力されています。

次に、同じリクエストで別の実行を実行しました。 もう一度1 ^ st ^実行を使用してステータス行を出力しました。 最後に、2回目の実行のステータス行を印刷しました。

説明したように、1 ^ st ^実行(アボートメソッド前の実行)の応答(アボートメソッドの後に書き込まれる2番目のステータス行を含む)が出力され、アボートメソッド後の現在のリクエストの後続の実行はすべて失敗します例外を呼び出します。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

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

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

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

     //Printing the method used
      System.out.println(httpget.getMethod());

     //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

     //Printing the status line
      System.out.println(httpresponse.getStatusLine());

      httpget.abort();
      System.out.println(httpresponse.getEntity().getContentLength());

     //Executing the Get request
      HttpResponse httpresponse2 = httpclient.execute(httpget);
      System.out.println(httpresponse2.getStatusLine());
   }
}

出力

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

On executing, the above program generates the following output.
GET
HTTP/1.1 200 OK
-1
Exception in thread "main" org.apache.http.impl.execchain.RequestAbortedException:
Request aborted
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:180)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at HttpGetExample.main(HttpGetExample.java:32)

Apache HttpClient-インターセプター

インターセプターは、要求または応答を妨害または変更するのに役立つものです。 プロトコルインターセプターは一般に、特定のヘッダーまたは関連するヘッダーのグループに基づいて動作します。 HttpClientライブラリは、インターセプターのサポートを提供します。

リクエストインターセプター

*HttpRequestInterceptor* インターフェースはリクエストインターセプターを表します。 このインターフェイスには、要求をインターセプトするコードチャンクを記述する必要があるプロセスと呼ばれるメソッドが含まれています。

クライアント側では、このメソッドはリクエストを検証/処理してからサーバーに送信し、サーバー側では、リクエストの本文を評価する前にこのメソッドを実行します。

リクエストインターセプターの作成

以下に示す手順に従って、要求インターセプターを作成できます。

  • ステップ1-HttpRequestInterceptor *のオブジェクトを作成します

抽象メソッドプロセスを実装して、HttpRequestInterceptorインターフェイスのオブジェクトを作成します。

HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
@Override
 public void process(HttpRequest request, HttpContext context) throws
HttpException, IOException {
  //Method implementation . . . . .
};

ステップ2-CloseableHttpClientオブジェクトのインスタンス化

以下に示すように、上記で作成したインターセプターを追加して、カスタム CloseableHttpClient オブジェクトを構築します-

//Creating a CloseableHttpClient object
CloseableHttpClient httpclient =
HttpClients.custom().addInterceptorFirst(requestInterceptor).build();

このオブジェクトを使用して、通常どおりリクエストの実行を実行できます。

次の例は、リクエストインターセプターの使用方法を示しています。 この例では、HTTP GETリクエストオブジェクトを作成し、3つのヘッダーを追加しました:sample-header、demoheader、およびtest-header。

インターセプターの* processor()メソッドでは、送信されたリクエストのヘッダーを検証しています。それらのヘッダーのいずれかが *sample-header である場合、そのヘッダーを削除し、その特定のリクエストのヘッダーのリストを表示しようとしています。

import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
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.message.BasicHeader;
import org.apache.http.protocol.HttpContext;

public class InterceptorsExample {

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

     //Creating an HttpRequestInterceptor
      HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
         @Override
         public void process(HttpRequest request, HttpContext context) throws
         HttpException, IOException {
            if(request.containsHeader("sample-header")) {
               System.out.println("Contains header sample-header, removing it..");
               request.removeHeaders("sample-header");
            }
           //Printing remaining list of headers
            Header[] headers= request.getAllHeaders();
            for (int i = 0; i<headers.length;i++) {
               System.out.println(headers[i].getName());
            }
         }
      };

     //Creating a CloseableHttpClient object
      CloseableHttpClient httpclient =
      HttpClients.custom().addInterceptorFirst(requestInterceptor).build();

     //Creating a request object
      HttpGet httpget1 = new HttpGet("https://www.finddevguides.com/");

     //Setting the header to it
      httpget1.setHeader(new BasicHeader("sample-header","My first header"));
      httpget1.setHeader(new BasicHeader("demo-header","My second header"));
      httpget1.setHeader(new BasicHeader("test-header","My third header"));

     //Executing the request
      HttpResponse httpresponse = httpclient.execute(httpget1);

     //Printing the status line
      System.out.println(httpresponse.getStatusLine());
   }
}

出力

上記のプログラムを実行すると、次の出力が生成されます-

Contains header sample-header, removing it..
demo-header
test-header
HTTP/1.1 200 OK

応答インターセプター

*HttpResponseInterceptor* インターフェースは、応答インターセプターを表します。 このインターフェイスには、* process()*と呼ばれるメソッドが含まれています。 このメソッドでは、応答をインターセプトするコードのチャンクを記述する必要があります。

サーバー側では、このメソッドは応答を検証/処理してからクライアントに送信し、クライアント側ではこのメソッドを実行してから応答の本文を評価します。

応答インターセプターの作成

次の手順に従って、応答インターセプターを作成できます-

ステップ1-HttpResponseInterceptorのオブジェクトを作成します

抽象メソッド process を実装して、 HttpResponseInterceptor インターフェイスのオブジェクトを作成します。

HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
   @Override
   public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
     //Method implementation . . . . . . . .
   }
};

ステップ2:CloseableHttpClientオブジェクトのインスタンス化

以下に示すように、上記で作成したインターセプターを追加して、カスタム CloseableHttpClient オブジェクトを構築します-

//Creating a CloseableHttpClient object
CloseableHttpClient httpclient =
HttpClients.custom().addInterceptorFirst(responseInterceptor).build();

このオブジェクトを使用して、通常どおりリクエストの実行を実行できます。

次の例は、応答インターセプターの使用方法を示しています。 この例では、プロセッサの応答に3つのヘッダー、sample-header、demo-header、およびtest-headerを追加しました。

リクエストを実行してレスポンスを取得した後、* getAllHeaders()*メソッドを使用して、レスポンスのすべてのヘッダーの名前を出力しました。

また、出力では、リスト内の3つのヘッダーの名前を確認できます。

import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
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.protocol.HttpContext;

public class ResponseInterceptorsExample {

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

     //Creating an HttpRequestInterceptor
      HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
         @Override
         public void process(HttpResponse response, HttpContext context) throws
         HttpException, IOException {
            System.out.println("Adding header sample_header, demo-header, test_header to the response");
            response.setHeader("sample-header", "My first header");
            response.setHeader("demo-header", "My second header");
            response.setHeader("test-header", "My third header");
         }
      };

     //Creating a CloseableHttpClient object
      CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(responseInterceptor).build();

     //Creating a request object
      HttpGet httpget1 = new HttpGet("https://www.finddevguides.com/");

     //Executing the request
      HttpResponse httpresponse = httpclient.execute(httpget1);

     //Printing remaining list of headers
      Header[] headers = httpresponse.getAllHeaders();

      for (int i = 0; i<headers.length;i++) {
         System.out.println(headers[i].getName());
      }
   }
}

出力

実行すると、上記のプログラムは次の結果を生成します-

On executing the above program generates the following output.
Adding header sample_header, demo-header, test_header to the response
Accept-Ranges
Access-Control-Allow-Headers
Access-Control-Allow-Origin
Cache-Control
Content-Type
Date
Expires
Last-Modified
Server
Vary
X-Cache
sample-header
demo-header
test-header

Apache HttpClient-ユーザー認証

HttpClientを使用すると、ユーザー名とパスワードが必要なWebサイトに接続できます。 この章では、ユーザー名とパスワードを要求するサイトに対してクライアント要求を実行する方法について説明します。

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

*CredentialsProvider* インターフェイスは、ユーザーログイン資格情報を保持するコレクションを保持します。 このインターフェイスのデフォルト実装である *BasicCredentialsProvider* クラスをインスタンス化することにより、オブジェクトを作成できます。
CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

ステップ2-資格情報の設定

  • setCredentials()*メソッドを使用して、CredentialsProviderオブジェクトに必要な資格情報を設定できます。

このメソッドは、以下に示すように2つのオブジェクトを受け入れます-

  • * AuthScopeオブジェクト*-ホスト名、ポート番号、認証スキーム名などの詳細を指定する認証スコープ。
  • 資格情報オブジェクト-資格情報(ユーザー名、パスワード)を指定します。

以下に示すように、ホストとプロキシの両方に対して* setCredentials()*メソッドを使用して資格情報を設定します-

credsProvider.setCredentials(new AuthScope("example.com", 80),
   new UsernamePasswordCredentials("user", "mypass"));
credsProvider.setCredentials(new AuthScope("localhost", 8000),
   new UsernamePasswordCredentials("abc", "passwd"));

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

*HttpClients* クラスの* custom()*メソッドを使用して *HttpClientBuilder* を作成します。
//Creating the HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();

ステップ4-クレデンシャルを設定する

  • setDefaultCredentialsProvider()*メソッドを使用して、上記で作成したcredentialsPoviderオブジェクトをHttpClientBuilderに設定できます。

前の手順で作成したCredentialProviderオブジェクトを、次に示すように* CredentialsProvider object()*メソッドに渡すことにより、クライアントビルダーに設定します。

clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);

ステップ5-CloseableHttpClientを構築する

*HttpClientBuilder* クラスの* build()*メソッドを使用して、 *CloseableHttpClient* オブジェクトをビルドします。
CloseableHttpClient httpclient = clientbuilder.build()

ステップ6-HttpGetオブジェクトを作成して実行する

HttpGetクラスをインスタンス化して、HttpRequestオブジェクトを作成します。 * execute()*メソッドを使用してこのリクエストを実行します。

//Creating a HttpGet object
HttpGet httpget = new HttpGet("https://www.finddevguides.com/");

//Executing the Get request
HttpResponse httpresponse = httpclient.execute(httpget);

以下は、ユーザー認証を必要とするターゲットサイトに対するHTTP要求の実行を示すサンプルプログラムです。

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

public class UserAuthenticationExample {

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

     //Create an object of credentialsProvider
      CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

     //Set the credentials
      AuthScope scope = new AuthScope("https://www.finddevguides.com/questions/", 80);

      Credentials credentials = new UsernamePasswordCredentials("USERNAME", "PASSWORD");
      credentialsPovider.setCredentials(scope,credentials);

     //Creating the HttpClientBuilder
      HttpClientBuilder clientbuilder = HttpClients.custom();

     //Setting the credentials
      clientbuilder = clientbuilder.setDefaultCredentialsProvider(credentialsPovider);

     //Building the CloseableHttpClient object
      CloseableHttpClient httpclient = clientbuilder.build();

     //Creating a HttpGet object
      HttpGet httpget = new HttpGet("https://www.finddevguides.com/questions/index.php");

     //Printing the method used
      System.out.println(httpget.getMethod());

     //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

     //Printing the status line
      System.out.println(httpresponse.getStatusLine());
      int statusCode = httpresponse.getStatusLine().getStatusCode();
      System.out.println(statusCode);

      Header[] headers= httpresponse.getAllHeaders();
      for (int i = 0; i<headers.length;i++) {
         System.out.println(headers[i].getName());
      }
   }
}

出力

実行すると、上記のプログラムは次の出力を生成します。

GET
HTTP/1.1 200 OK
200

Apache HttpClient-プロキシの使用

プロキシサーバーは、クライアントとインターネット間の仲介サーバーです。 プロキシサーバーは、次の基本的な機能を提供します-

  • ファイアウォールおよびネットワークデータフィルタリング
  • ネットワーク接続の共有
  • データキャッシング

HttpClientライブラリを使用すると、プロキシを使用してHTTP要求を送信できます。 以下の手順に従ってください-

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

(リクエストを送信する必要がある)プロキシホストの名前を表す文字列パラメーターをコンストラクターに渡すことにより、 org.apache.http パッケージの HttpHost クラスをインスタンス化します。

//Creating an HttpHost object for proxy
HttpHost proxyHost = new HttpHost("localhost");

同様に、リクエストを送信する必要のあるターゲットホストを表す別のHttpHostオブジェクトを作成します。

//Creating an HttpHost object for target
HttpHost targetHost = new HttpHost("google.com");

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

*HttpRoutePlanner* インターフェイスは、指定されたホストへのルートを計算します。 このインターフェイスの実装である *DefaultProxyRoutePlanner* クラスをインスタンス化して、このインターフェイスのオブジェクトを作成します。 そのコンストラクタへのパラメータとして、上記で作成されたプロキシホストを渡します-
//creating a RoutePlanner object
HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost);

ステップ3-ルートプランナーをクライアントビルダーに設定する

*HttpClients* クラスの* custom()*メソッドを使用して *HttpClientBuilder* オブジェクトを作成し、このオブジェクトに* setRoutePlanner()*メソッドを使用して、上記で作成したルートプランナーを設定します。
//Setting the route planner to the HttpClientBuilder object
HttpClientBuilder clientBuilder = HttpClients.custom();

clientBuilder = clientBuilder.setRoutePlanner(routePlanner);

ステップ4-CloseableHttpClientオブジェクトを構築する

  • build()メソッドを呼び出して、 *CloseableHttpClient オブジェクトをビルドします。
//Building a CloseableHttpClient
CloseableHttpClient httpClient = clientBuilder.build();

ステップ5-HttpGetobjectを作成する

*HttpGet* クラスをインスタンス化して、HTTP GETリクエストを作成します。
//Creating an HttpGet object
HttpGet httpGet = new HttpGet("/");

ステップ6-リクエストを実行する

  • execute()メソッドのバリアントの1つは、 *HttpHost および HttpRequest オブジェクトを受け入れ、要求を実行します。 このメソッドを使用してリクエストを実行します-
//Executing the Get request
HttpResponse httpResponse = httpclient.execute(targetHost, httpGet);

次の例は、プロキシを介してサーバーにHTTP要求を送信する方法を示しています。 この例では、localhost経由でgoogle.comにHTTP GETリクエストを送信しています。 応答のヘッダーと応答の本文を印刷しました。

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.util.EntityUtils;

public class RequestViaProxyExample {

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

     //Creating an HttpHost object for proxy
      HttpHost proxyhost = new HttpHost("localhost");

     //Creating an HttpHost object for target
      HttpHost targethost = new HttpHost("google.com");

     //creating a RoutePlanner object
      HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost);

     //Setting the route planner to the HttpClientBuilder object
      HttpClientBuilder clientBuilder = HttpClients.custom();
      clientBuilder = clientBuilder.setRoutePlanner(routePlanner);

     //Building a CloseableHttpClient
      CloseableHttpClient httpclient = clientBuilder.build();

     //Creating an HttpGet object
      HttpGet httpget = new HttpGet("/");

     //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(targethost, httpget);

     //Printing the status line
      System.out.println(httpresponse.getStatusLine());

     //Printing all the headers of the response
      Header[] headers = httpresponse.getAllHeaders();

      for (int i = 0; i < headers.length; i++) {
         System.out.println(headers[i]);
      }

     //Printing the body of the response
      HttpEntity entity = httpresponse.getEntity();

      if (entity != null) {
         System.out.println(EntityUtils.toString(entity));
      }
   }
}

出力

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

HTTP/1.1 200 OK
Date: Sun, 23 Dec 2018 10:21:47 GMT
Server: Apache/2.4.9 (Win64) PHP/5.5.13
Last-Modified: Tue, 24 Jun 2014 10:46:24 GMT
ETag: "2e-4fc92abc3c000"
Accept-Ranges: bytes
Content-Length: 46
Content-Type: text/html
<html><body><h1>It works!</h1></body></html>

Apache HttpClient-プロキシ認証

この章では、例を使用して、ユーザー名とパスワードを使用して認証されたHttpRequestを作成し、プロキシを介してターゲットホストにトンネルする方法を学習します。

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

CredentialsProvider Interfaceは、ユーザーログイン資格情報を保持するコレクションを維持します。 このインターフェイスのデフォルト実装であるBasicCredentialsProviderクラスをインスタンス化することにより、そのオブジェクトを作成できます。

CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

ステップ2-資格情報を設定する

  • setCredentials()*メソッドを使用して、CredentialsProviderオブジェクトに必要な資格情報を設定できます。 このメソッドは、2つのオブジェクトを受け入れます-
  • * AuthScopeオブジェクト*-ホスト名、ポート番号、認証スキーム名などの詳細を指定する認証スコープ。
  • 資格情報オブジェクト-資格情報(ユーザー名、パスワード)を指定します。 以下に示すように、ホストとプロキシの両方に対して* setCredentials()*メソッドを使用して資格情報を設定します。
credsProvider.setCredentials(new AuthScope("example.com", 80), new
   UsernamePasswordCredentials("user", "mypass"));
credsProvider.setCredentials(new AuthScope("localhost", 8000), new
   UsernamePasswordCredentials("abc", "passwd"));

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

以下に示すように HttpClients クラスの* custom()メソッドを使用して *HttpClientBuilder を作成します-

//Creating the HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();

ステップ4-CredentialsProviderの設定

  • setDefaultCredentialsProvider()メソッドを使用して、CredentialsProviderオブジェクトをHttpClientBuilderオブジェクトに設定できます。 以前に作成した *CredentialsProvider オブジェクトをこのメソッドに渡します。
clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);

ステップ5-CloseableHttpClientを構築する

  • build()メソッドを使用して *CloseableHttpClient オブジェクトをビルドします。
CloseableHttpClient httpclient = clientbuilder.build();

ステップ6-プロキシおよびターゲットホストを作成する

*HttpHost* クラスをインスタンス化して、ターゲットおよびプロキシホストを作成します。
//Creating the target and proxy hosts
HttpHost target = new HttpHost("example.com", 80, "http");
HttpHost proxy = new HttpHost("localhost", 8000, "http");

ステップ7-プロキシを設定し、RequestConfigオブジェクトを構築します

  • custom()メソッドを使用して *RequestConfig.Builder オブジェクトを作成します。 * setProxy()メソッドを使用して、以前に作成したproxyHostオブジェクトを *RequestConfig.Builder に設定します。 最後に、* build()メソッドを使用して *RequestConfig オブジェクトをビルドします。
RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();
reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);
RequestConfig config = reqconfigconbuilder.build();

ステップ8-HttpGet要求オブジェクトを作成し、それに構成オブジェクトを設定します。

HttpGetクラスをインスタンス化して HttpGet オブジェクトを作成します。 * setConfig()*メソッドを使用して、前の手順で作成した構成オブジェクトをこのオブジェクトに設定します。

//Create the HttpGet request object
HttpGet httpGet = new HttpGet("/");

//Setting the config to the request
httpget.setConfig(config);

ステップ9-リクエストを実行する

HttpHostオブジェクト(ターゲット)とリクエスト(HttpGet)をパラメーターとして* execute()*メソッドに渡すことにより、リクエストを実行します。

HttpResponse httpResponse = httpclient.execute(targetHost, httpget);

次の例は、ユーザー名とパスワードを使用してプロキシ経由でHTTP要求を実行する方法を示しています。

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

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

     //Creating the CredentialsProvider object
      CredentialsProvider credsProvider = new BasicCredentialsProvider();

     //Setting the credentials
      credsProvider.setCredentials(new AuthScope("example.com", 80),
         new UsernamePasswordCredentials("user", "mypass"));
      credsProvider.setCredentials(new AuthScope("localhost", 8000),
         new UsernamePasswordCredentials("abc", "passwd"));

     //Creating the HttpClientBuilder
      HttpClientBuilder clientbuilder = HttpClients.custom();

     //Setting the credentials
      clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);

     //Building the CloseableHttpClient object
      CloseableHttpClient httpclient = clientbuilder.build();


     //Create the target and proxy hosts
      HttpHost targetHost = new HttpHost("example.com", 80, "http");
      HttpHost proxyHost = new HttpHost("localhost", 8000, "http");

     //Setting the proxy
      RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();
      reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);
      RequestConfig config = reqconfigconbuilder.build();

     //Create the HttpGet request object
      HttpGet httpget = new HttpGet("/");

     //Setting the config to the request
      httpget.setConfig(config);

     //Printing the status line
      HttpResponse response = httpclient.execute(targetHost, httpget);
      System.out.println(response.getStatusLine());

   }
}

出力

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

HTTP/1.1 200 OK

Apache HttpClient-フォームベースのログイン

HttpClientライブラリを使用すると、リクエストを送信したり、パラメータを渡してフォームにログインしたりできます。

以下の手順に従って、フォームにログインします。

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

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

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

クラス RequestBuilder は、パラメーターを追加して要求を作成するために使用されます。 リクエストタイプがPUTまたはPOSTの場合、リクエストにパラメーターをURLエンコードエンティティとして追加します

post()メソッドを使用して、(POSTタイプの)RequestBuilderオブジェクトを作成します。

//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post();

ステップ3-UriとパラメーターをRequestBuilderに設定します。

RequestBuilderクラスの* setUri()および addParameter()*メソッドを使用して、URIおよびパラメーターをRequestBuilderオブジェクトに設定します。

//Set URI and parameters
RequestBuilder reqbuilder = reqbuilder.setUri("http://httpbin.org/post");
reqbuilder = reqbuilder1.addParameter("Name", "username").addParameter("password", "password");

ステップ4-HttpUriRequestオブジェクトを構築する

必須パラメーターを設定したら、* build()メソッドを使用して *HttpUriRequest オブジェクトをビルドします。

//Building the HttpUriRequest object
HttpUriRequest httppost = reqbuilder2.build();

ステップ5-リクエストを実行する

CloseableHttpClientオブジェクトのexecuteメソッドは、HttpUriRequest(インターフェイス)オブジェクト(つまり、 HttpGet、HttpPost、HttpPut、HttpHeadなど)と応答オブジェクトを返します。

前の手順で作成したHttpUriRequestを* execute()*メソッドに渡して実行します。

//Execute the request
HttpResponse httpresponse = httpclient.execute(httppost);

次の例は、ログイン資格情報を送信してフォームにログオンする方法を示しています。 ここでは、2つのパラメーター-*ユーザー名とパスワード*をフォームに送信し、メッセージエンティティとリクエストのステータスを出力しようとしました。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;

public class FormLoginExample {

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

     //Creating CloseableHttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

     //Creating the RequestBuilder object
      RequestBuilder reqbuilder = RequestBuilder.post();

     //Setting URI and parameters
      RequestBuilder reqbuilder1 = reqbuilder.setUri("http://httpbin.org/post");
      RequestBuilder reqbuilder2 = reqbuilder1.addParameter("Name",
         "username").addParameter("password", "password");

     //Building the HttpUriRequest object
      HttpUriRequest httppost = reqbuilder2.build();

     //Executing the request
      HttpResponse httpresponse = httpclient.execute(httppost);

     //Printing the status and the contents of the response
      System.out.println(EntityUtils.toString(httpresponse.getEntity()));
      System.out.println(httpresponse.getStatusLine());
   }
}

出力

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

{
   "args": {},
   "data": "",
   "files": {},
   "form": {
      "Name": "username",
      "password": "password"
   },
   "headers": {
      "Accept-Encoding": "gzip,deflate",
      "Connection": "close",
      "Content-Length": "31",
      "Content-Type": "application/x-www-form-urlencoded; charset = UTF-8",
      "Host": "httpbin.org",
      "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
   },
   "json": null,
   "origin": "117.216.245.180",
   "url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK

Cookieを使用したフォームログイン

フォームがデフォルトの CloseableHttpClient オブジェクトを作成する代わりに、Cookieを保存する場合。

  • BasicCookieStoreクラスをインスタンス化して、CookieStoreオブジェクトを作成します。
//Creating a BasicCookieStore object
BasicCookieStore cookieStore = new BasicCookieStore();
  • HttpClients クラスの* custom()*メソッドを使用してHttpClientBuilder *を作成します。
//Creating an HttpClientBuilder object
HttpClientBuilder clientbuilder = HttpClients.custom();
  • setDefaultCookieStore()メソッドを使用して、Cookieストアをクライアントビルダーに設定します。
//Setting default cookie store to the client builder object
Clientbuilder = clientbuilder.setDefaultCookieStore(cookieStore);
  • build()メソッドを使用して *CloseableHttpClient オブジェクトをビルドします。
//Building the CloseableHttpClient object
CloseableHttpClient httpclient = clientbuilder1.build();

リクエストの実行を渡すことにより、上記で指定した HttpUriRequest オブジェクトを作成します。

ページにCookieが保存されている場合、渡したパラメーターはCookieストアに追加されます。

パラメータを見ることができる CookieStore オブジェクトの内容を印刷できます(以前のページとともに、ケースに保存されたページ)。

Cookieを印刷するには、* getCookies()メソッドを使用して *CookieStore オブジェクトからすべてのCookieを取得します。 このメソッドは List オブジェクトを返します。 イテレータを使用して、以下に示すようにリストオブジェクトの内容を印刷します-

//Printing the cookies
List list = cookieStore.getCookies();

System.out.println("list of cookies");
Iterator it = list.iterator();
if(it.hasNext()) {
   System.out.println(it.next());
}

Apache HttpClient-クッキー管理

Cookieは、クライアントコンピューターに保存されるテキストファイルであり、さまざまな情報追跡目的で保持されます。

HttpClientは、Cookieを作成および管理できるCookieのサポートを提供します。

クッキーを作成する

以下の手順に従って、HttpClientライブラリを使用してCookieを作成します。

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

*CookieStore* インターフェースは、Cookieオブジェクトの抽象ストアを表します。 このインターフェイスのデフォルト実装である *BasicCookieStore* クラスをインスタンス化することにより、Cookieストアを作成できます。
//Creating the CookieStore object
CookieStore cookieStore = new BasicCookieStore();

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

Cookieの機能に加えて、ClientCookieはサーバー内の元のCookieを取得できます。 BasicClientCookie クラスをインスタンス化することにより、クライアントCookieを作成できます。 このクラスのコンストラクターには、特定のCookieに保存するキーと値のペアを渡す必要があります。

//Creating client cookie
BasicClientCookie clientCookie = new BasicClientCookie("name","Raju");

ステップ3-Cookieに値を設定します

クライアントCookieに対して、それぞれの方法を使用して、パス、値、バージョン、有効期限、ドメイン、コメント、および属性を設定/削除できます。

Calendar myCal = new GregorianCalendar(2018, 9, 26);
Date expiryDate = myCal.getTime();
clientcookie.setExpiryDate(expiryDate);
clientcookie.setPath("/");
clientcookie.setSecure(true);
clientcookie.setValue("25");
clientcookie.setVersion(5);

手順4-CookieをCookieストアに追加する

*BasicCookieStore* クラスの* addCookie()*メソッドを使用して、CookieストアにCookieを追加できます。

必要なCookieを Cookiestore に追加します。

//Adding the created cookies to cookie store
cookiestore.addCookie(clientcookie);

次の例は、Cookieを作成し、Cookieストアに追加する方法を示しています。 ここでは、ドメインとパスの値を設定してCookieストア、Cookieの束を作成し、Cookieストアに追加しました。

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;

public class CookieHandlingExample {

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

     //Creating the CookieStore object
      CookieStore cookiestore = new BasicCookieStore();

     //Creating client cookies
      BasicClientCookie clientcookie1 = new BasicClientCookie("name","Raju");
      BasicClientCookie clientcookie2 = new BasicClientCookie("age","28");
      BasicClientCookie clientcookie3 = new BasicClientCookie("place","Hyderabad");

     //Setting domains and paths to the created cookies
      clientcookie1.setDomain(".sample.com");
      clientcookie2.setDomain(".sample.com");
      clientcookie3.setDomain(".sample.com");

      clientcookie1.setPath("/");
      clientcookie2.setPath("/");
      clientcookie3.setPath("/");

     //Adding the created cookies to cookie store
      cookiestore.addCookie(clientcookie1);
      cookiestore.addCookie(clientcookie2);
      cookiestore.addCookie(clientcookie3);
   }
}

クッキーを取得する

*asicCookieStore* クラスの* getCookies()*メソッドを使用して、Cookieストアに追加されたCookieを取得できます。 このメソッドは、Cookieストア内のすべてのCookieを保持するリストを返します。

以下に示すように、イテレータを使用してクッキーストアの内容を印刷できます-

//Retrieving the cookies
List list = cookieStore.getCookies();

//Creating an iterator to the obtained list
Iterator it = list.iterator();
while(it.hasNext()) {
   System.out.println(it.next());
}

次の例は、CookieストアからCookieを取得する方法を示しています。 ここでは、大量のCookieをCookieストアに追加し、それらを取得しています。

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;

public class CookieHandlingExample {

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

     //Creating the CookieStore object
      CookieStore cookiestore = new BasicCookieStore();

     //Creating client cookies
      BasicClientCookie clientcookie1 = new BasicClientCookie("name","Raju");
      BasicClientCookie clientcookie2 = new BasicClientCookie("age","28");
      BasicClientCookie clientcookie3 = new BasicClientCookie("place","Hyderabad");

     //Setting domains and paths to the created cookies
      clientcookie1.setDomain(".sample.com");
      clientcookie2.setDomain(".sample.com");
      clientcookie3.setDomain(".sample.com");

      clientcookie1.setPath("/");
      clientcookie2.setPath("/");
      clientcookie3.setPath("/");

     //Adding the created cookies to cookie store
      cookiestore.addCookie(clientcookie1);
      cookiestore.addCookie(clientcookie2);
      cookiestore.addCookie(clientcookie3);
   }
}

出力

実行すると、このプログラムは次の出力を生成します-

[version: 0][name: age][value: 28][domain: .sample.com][path:/][expiry: null]
[version: 0][name: name][value: Raju][domain: my.example.com][path:/][expiry:
null]
[version: 0][name: place][value: Hyderabad][domain: .sample.com][path:
/][expiry: null]

Apache HttpClient-複数のスレッド

マルチスレッドプログラムには、同時に実行できる2つ以上の部分が含まれており、各部分は同時に使用可能なリソースを最適に使用して異なるタスクを処理できます。

マルチスレッドHttpClientプログラムを記述することにより、複数のスレッドからリクエストを実行できます。

スレッドから複数のクライアントリクエストを連続して実行する場合は、 ClientConnectionPoolManager を作成する必要があります。 HttpClientConnections のプールを維持し、スレッドからの複数のリクエストを処理します。

接続マネージャーは、ルートに基づいて接続をプールします。 マネージャに特定のルートへの接続がある場合、マネージャは、新しい接続を作成する代わりに、プールから既存の接続をリースすることにより、それらのルートで新しいリクエストを処理します。

手順に従って、複数のスレッドからリクエストを実行します-

手順1-クライアント接続プールマネージャーの作成

*PoolingHttpClientConnectionManager* クラスをインスタンス化して、クライアント接続プールマネージャーを作成します。
PoolingHttpClientConnectionManager connManager = new
   PoolingHttpClientConnectionManager();

ステップ2-接続の最大数を設定する

  • setMaxTotal()*メソッドを使用して、プール内の接続の最大数を設定します。
//Set the maximum number of connections in the pool
connManager.setMaxTotal(100);

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

以下に示すように、* setConnectionManager()メソッドを使用して接続マネージャーを設定することにより、 *ClientBuilder オブジェクトを作成します-

HttpClientBuilder clientbuilder =
HttpClients.custom().setConnectionManager(connManager);

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

目的のURIをコンストラクターにパラメーターとして渡すことにより、HttpGetクラスをインスタンス化します。

HttpGet httpget1 = new HttpGet("URI1");
HttpGet httpget2 = new HttpGet("URI2");
. . . . . . . . . . . .

ステップ5-runメソッドの実装

クラスを作成し、スレッド(スレッドクラスを拡張するか、Runnableインターフェイスを実装することで)にし、runメソッドを実装したことを確認してください。

public class ClientMultiThreaded extends Thread {
   public void run() {
     //Run method implementation . . . . . . . . . .
   }
}

ステップ6-スレッドオブジェクトの作成

上記で作成したThreadクラス(ClientMultiThreaded)をインスタンス化して、スレッドオブジェクトを作成します。

HttpClientオブジェクト、それぞれのHttpGetオブジェクト、およびIDを表す整数をこれらのスレッドに渡します。

ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1);
ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2);
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ステップ7-スレッドを開始して参加する

  • start()*メソッドを使用してすべてのスレッドを開始し、join * method()*を使用してそれらを結合します。
thread1.start();
thread2.start();
. . . . . . . .
thread1.join();
thread2.join();
. . . . . . . . . . . .

ステップ8-メソッド実装の実行

runメソッド内で、リクエストを実行し、レスポンスを取得して結果を出力します。

次の例は、複数のスレッドからのHTTP要求の同時実行を示しています。 この例では、さまざまなスレッドからさまざまな要求を実行し、各クライアントが読み取ったステータスとバイト数を出力しようとしています。

import org.apache.http.HttpEntity;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

public class ClientMultiThreaded extends Thread {
   CloseableHttpClient httpClient;
   HttpGet httpget;
   int id;

   public ClientMultiThreaded(CloseableHttpClient httpClient, HttpGet httpget,
   int id) {
      this.httpClient = httpClient;
      this.httpget = httpget;
      this.id = id;
   }
   @Override
   public void run() {
      try{
        //Executing the request
         CloseableHttpResponse httpresponse = httpClient.execute(httpget);

        //Displaying the status of the request.
         System.out.println("status of thread "+id+":"+httpresponse.getStatusLine());

        //Retrieving the HttpEntity and displaying the no.of bytes read
         HttpEntity entity = httpresponse.getEntity();
         if (entity != null) {
            System.out.println("Bytes read by thread thread "+id+":
               "+EntityUtils.toByteArray(entity).length);
         }
      }catch(Exception e) {
         System.out.println(e.getMessage());
      }
   }

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

     //Creating the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class.
      PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

     //Set the maximum number of connections in the pool
      connManager.setMaxTotal(100);

     //Create a ClientBuilder Object by setting the connection manager
      HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager);

     //Build the CloseableHttpClient object using the build() method.
      CloseableHttpClient httpclient = clientbuilder.build();

     //Creating the HttpGet requests
      HttpGet httpget1 = new HttpGet("http://www.finddevguides.com/");
      HttpGet httpget2 = new HttpGet("http://www.google.com/");
      HttpGet httpget3 = new HttpGet("https://www.qries.com/");
      HttpGet httpget4 = new HttpGet("https://in.yahoo.com/");

     //Creating the Thread objects
      ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1);
      ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2);
      ClientMultiThreaded thread3 = new ClientMultiThreaded(httpclient,httpget3, 3);
      ClientMultiThreaded thread4 = new ClientMultiThreaded(httpclient,httpget4, 4);

     //Starting all the threads
      thread1.start();
      thread2.start();
      thread3.start();
      thread4.start();

     //Joining all the threads
      thread1.join();
      thread2.join();
      thread3.join();
      thread4.join();
   }
}

出力

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

status of thread 1: HTTP/1.1 200 OK
Bytes read by thread thread 1: 36907
status of thread 2: HTTP/1.1 200 OK
Bytes read by thread thread 2: 13725
status of thread 3: HTTP/1.1 200 OK
Bytes read by thread thread 3: 17319
status of thread 4: HTTP/1.1 200 OK
Bytes read by thread thread 4: 127018

Apache HttpClient-カスタムSSLコンテキスト

Secure Socket Layerを使用すると、クライアントとサーバー間に安全な接続を確立できます。 クレジットカード番号、ユーザー名、パスワード、ピンなどの機密情報を保護するのに役立ちます。

*HttpClient* ライブラリを使用して独自のSSLコンテキストを作成することにより、接続をより安全にすることができます。

以下に示す手順に従って、HttpClientライブラリを使用してSSLContextをカスタマイズします-

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

*SSLContextBuilder* は、SSLContextオブジェクトのビルダーです。 *SSLContexts* クラスの* custom()*メソッドを使用してオブジェクトを作成します。
//Creating SSLContextBuilder object
SSLContextBuilder SSLBuilder = SSLContexts.custom();

ステップ2-キーストアをロードする

パス Java_home_directory/jre/lib/security/ で、cacertsという名前のファイルを見つけることができます。 これをキーストアファイル(拡張子.jks)として保存します。 SSLContextBuilder クラスの* loadTrustMaterial()メソッドを使用して、キーストアファイルとそのパスワード(デフォルトでは *changeit )をロードします。

//Loading the Keystore file
File file = new File("mykeystore.jks");
SSLBuilder = SSLBuilder.loadTrustMaterial(file, "changeit".toCharArray());

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

SSLContextオブジェクトは、セキュアソケットプロトコルの実装を表します。 * build()*メソッドを使用してSSLContextを構築します。

//Building the SSLContext
SSLContext sslContext = SSLBuilder.build();

ステップ4-SSLConnectionSocketFactoryオブジェクトの作成

*SSLConnectionSocketFactory* は、TSLおよびSSL接続用の階層化されたソケットファクトリです。 これを使用すると、信頼できる証明書のリストを使用してHttpsサーバーを検証し、指定されたHttpsサーバーを認証できます。

これはさまざまな方法で作成できます。 SSLConnectionSocketFactory オブジェクトの作成方法に応じて、すべてのホストを許可したり、自己署名証明書のみを許可したり、特定のプロトコルのみを許可したりできます。

特定のプロトコルのみを許可するには、SSLContextオブジェクトを渡すことで *SSLConnectionSocketFactory オブジェクトを作成します。プロトコルを表す文字列配列をサポートする必要があり、暗号スーツを表す文字列配列をサポートする必要があり、HostnameVerifierオブジェクトをコンストラクタに渡します。

new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
   SSLConnectionSocketFactory.getDefaultHostnameVerifier());

すべてのホストを許可するには、 SSLContextオブジェクトと NoopH​​ostnameVerifier オブジェクトを渡すことで SSLConnectionSocketFactory オブジェクトを作成します。

//Creating SSLConnectionSocketFactory SSLConnectionSocketFactory object
SSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());

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

*HttpClients* クラスの* custom()*メソッドを使用して、HttpClientBuilderオブジェクトを作成します。
//Creating HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();

ステップ6-SSLConnectionSocketFactoryオブジェクトを設定する

  • setSSLSocketFactory()メソッドを使用して、SSLConnectionSocketFactoryオブジェクトを *HttpClientBuilder に設定します。
//Setting the SSLConnectionSocketFactory
clientbuilder = clientbuilder.setSSLSocketFactory(sslConSocFactory);

ステップ7-CloseableHttpClientオブジェクトを構築する

  • build()メソッドを呼び出して、 *CloseableHttpClient オブジェクトをビルドします。
//Building the CloseableHttpClient
CloseableHttpClient httpclient = clientbuilder.build();

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

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

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

//Creating the HttpGet request
HttpGet httpget = new HttpGet("https://example.com/");

ステップ9-リクエストを実行する

  • execute()*メソッドを使用してリクエストを実行します。
//Executing the request
HttpResponse httpresponse = httpclient.execute(httpget);

次の例は、SSLContrextのカスタマイズを示しています-

import java.io.File;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

public class ClientCustomSSL {

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

     //Creating SSLContextBuilder object
      SSLContextBuilder SSLBuilder = SSLContexts.custom();

     //Loading the Keystore file
      File file = new File("mykeystore.jks");
      SSLBuilder = SSLBuilder.loadTrustMaterial(file,
         "changeit".toCharArray());

     //Building the SSLContext usiong the build() method
      SSLContext sslcontext = SSLBuilder.build();

     //Creating SSLConnectionSocketFactory object
      SSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());

     //Creating HttpClientBuilder
      HttpClientBuilder clientbuilder = HttpClients.custom();

     //Setting the SSLConnectionSocketFactory
      clientbuilder = clientbuilder.setSSLSocketFactory(sslConSocFactory);

     //Building the CloseableHttpClient
      CloseableHttpClient httpclient = clientbuilder.build();

     //Creating the HttpGet request
      HttpGet httpget = new HttpGet("https://example.com/");

     //Executing the request
      HttpResponse httpresponse = httpclient.execute(httpget);

     //printing the status line
      System.out.println(httpresponse.getStatusLine());

     //Retrieving the HttpEntity and displaying the no.of bytes read
      HttpEntity entity = httpresponse.getEntity();
      if (entity != null) {
         System.out.println(EntityUtils.toByteArray(entity).length);
      }
   }
}

出力

実行すると、上記のプログラムは次の出力を生成します。

HTTP/1.1 200 OK
1270

Apache HttpClient-マルチパートアップロード

HttpClientを使用して、マルチパートアップロードを実行できます。つまり、大きなオブジェクトを小さなパーツにアップロードできます。 この章では、単純なテキストファイルをアップロードすることにより、HTTPクライアントでのマルチパートアップロードを示します。

一般に、マルチパートアップロードには3つのパートが含まれます。

  • アップロードの開始
  • オブジェクトパーツのアップロード
  • マルチパートアップロードの完了

HttpClientを使用したマルチパートアップロードの場合、以下の手順に従う必要があります-

  • マルチパートビルダーを作成します。
  • 必要なパーツを追加します。
  • ビルドを完了し、マルチパートHttpEntityを取得します。
  • 上記のマルチパートエンティティを設定して、リクエストをビルドします。
  • リクエストを実行します。

HttpClientライブラリを使用してマルチパートエンティティをアップロードする手順は次のとおりです。

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

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

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

*FileBody* クラスは、ファイルによって裏付けられたバイナリ本文部分を表します。 *File* オブジェクトとコンテンツのタイプを表す *ContentType* オブジェクトを渡すことにより、このクラスをインスタンス化します。
//Creating a File object
File file = new File("sample.txt");

//Creating the FileBody object
FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);

ステップ3-MultipartEntityBuilderを作成する

*MultipartEntityBuilder* クラスは、マルチパートの *HttpEntity* オブジェクトを構築するために使用されます。 (同じクラスの)* create()*メソッドを使用してオブジェクトを作成します。
//Creating the MultipartEntityBuilder
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();

ステップ4-モードを設定する

*MultipartEntityBuilder* には、STRICT、RFC6532、およびBROWSER_COMPATIBLEの3つのモードがあります。 * setMode()*メソッドを使用して、目的のモードに設定します。
//Setting the mode
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

手順5-必要なさまざまなパーツを追加する

メソッド* addTextBody()、addPart()、および addBinaryBody()を使用すると、単純なテキスト、ファイル、ストリーム、およびその他のオブジェクトを *MultipartBuilder に追加できます。 これらの方法を使用して、目的のコンテンツを追加します。

//Adding text
entitybuilder.addTextBody("sample_text", "This is the text part of our file");
//Adding a file
entitybuilder.addBinaryBody("image", new File("logo.png"));

ステップ6-単一のエンティティの構築

*MultipartEntityBuilder* クラスの* build()*メソッドを使用して、これらすべてのパーツを単一のエンティティにビルドできます。 このメソッドを使用して、すべてのパーツを単一の *HttpEntity* にビルドします。
//Building a single entity using the parts
HttpEntity mutiPartHttpEntity = entityBuilder.build();

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

クラス RequestBuilder は、パラメーターを追加して要求を作成するために使用されます。 要求のタイプがPUTまたはPOSTの場合、URLエンコードされたエンティティとして要求にパラメーターを追加します。

  • post()*メソッドを使用して、(POSTタイプの)RequestBuilderオブジェクトを作成します。 そして、リクエストの送信先のUriをパラメーターとして渡します。
//Building the post request object
RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");

ステップ8-エンティティオブジェクトをRequestBuilderに設定する

*RequestBuilder* クラスの* setEntity()*メソッドを使用して、上記で作成したマルチパートエンティティをRequestBuilderに設定します。
//Setting the entity object to the RequestBuilder
reqbuilder.setEntity(mutiPartHttpEntity);

ステップ9-HttpUriRequestを構築する

*RequestBuilder* クラスの* build()*メソッドを使用して、 *HttpUriRequest* 要求オブジェクトを作成します。
//Building the request
HttpUriRequest multipartRequest = reqbuilder.build();

ステップ10-リクエストを実行する

  • execute()*メソッドを使用して、前の手順で作成したリクエストを実行します(このメソッドへのパラメーターとしてリクエストをバイパスします)。
//Executing the request
HttpResponse httpresponse = httpclient.execute(multipartRequest);

次の例は、HttpClientライブラリを使用してマルチパートリクエストを送信する方法を示しています。 この例では、ファイルを基にしたマルチパートリクエストを送信しようとしています。

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class MultipartUploadExample {

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

     //Creating CloseableHttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

     //Creating a file object
      File file = new File("sample.txt");

     //Creating the FileBody object
      FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);

     //Creating the MultipartEntityBuilder
      MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();

     //Setting the mode
      entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

     //Adding text
      entitybuilder.addTextBody("sample_text", "This is the text part of our file");

     //Adding a file
      entitybuilder.addBinaryBody("image", new File("logo.png"));

     //Building a single entity using the parts
      HttpEntity mutiPartHttpEntity = entitybuilder.build();

     //Building the RequestBuilder request object
      RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post");

     //Set the entity object to the RequestBuilder
      reqbuilder.setEntity(mutiPartHttpEntity);

     //Building the request
      HttpUriRequest multipartRequest = reqbuilder.build();

     //Executing the request
      HttpResponse httpresponse = httpclient.execute(multipartRequest);

     //Printing the status and the contents of the response
      System.out.println(EntityUtils.toString(httpresponse.getEntity()));
      System.out.println(httpresponse.getStatusLine());
   }
}

出力

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

{
   "args": {},
   "data": "",
   "files": {
      "image": "data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE
      lFTkSuQmCC"
   },
   "form": {
      "sample_text": "This is the text part of our file"
   },
   "headers": {
      "Accept-Encoding": "gzip,deflate",
      "Connection": "close",
      "Content-Length": "11104",
      "Content-Type": "multipart/form-data;
      boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt",
      "Host": "httpbin.org",
      "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)"
   },
   "json": null,
   "origin": "117.216.245.180",
   "url": "http://httpbin.org/post"
}
HTTP/1.1 200 OK