Apache HttpClientの例 – CloseableHttpClient

Apache HttpClientを使用すると、クライアントコードからサーバーへのHTTPリクエストを送信することができます。前回のチュートリアルでは、Javaプログラム自体からGETおよびPOSTのHTTPリクエスト操作を実行するためにHttpURLConnectionの使用方法を見ました。今日は同じ例題プロジェクトを使用して、Apache HttpClientを使用してGETおよびPOSTのリクエスト操作を実行します。

アパッチのHttpClient

GETとPOSTリクエストの詳細を理解するために、以前の例も参照することを強くお勧めします。 Apache HttpClientは、Javaプログラム自体からHTTPリクエストを送信するために非常に広く使用されています。 Mavenを使用している場合は、以下の依存関係を追加することで、Apache HttpClientの使用に必要なすべての他の依存関係が含まれます。

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.4</version>
</dependency>

しかし、Mavenを使用していない場合は、プロジェクトのビルドパスに以下のJARファイルを追加する必要があります。

    1. httpclient-4.4.jar

 

    1. httpcore-4.4.jar

 

    1. commons-logging-1.2.jar

 

    1. commons-codec-1.9.jar

httpclient-4.4.jar
httpcore-4.4.jar
commons-logging-1.2.jar
commons-codec-1.9.jar

もしApache HttpClientの他のバージョンを使用していて、かつMavenを使っていない場合、以下の画像に示されているように一時的なMavenプロジェクトを作成し、互換性のあるjarファイルのリストを取得してください。そして、それらのjarファイルをプロジェクトのlibディレクトリにコピーするだけで、互換性の問題を回避することができます。また、jarファイルをインターネットから探してダウンロードする手間も省けます。必要な依存関係が揃ったので、以下にApache HttpClientを使用してGETリクエストとPOSTリクエストを送信するための手順を示します。

    1. ヘルパークラスHttpClientsを使用してCloseableHttpClientのインスタンスを作成します。

 

    1. HTTPリクエストのタイプに基づいて、HttpGetまたはHttpPostのインスタンスを作成します。

 

    1. User-Agent、Accept-Encodingなどの必要なヘッダーを追加するためにaddHeaderメソッドを使用します。

 

    1. POSTの場合は、NameValuePairのリストを作成し、すべてのフォームパラメータを追加します。それをHttpPostエンティティに設定します。

 

    1. HttpGetまたはHttpPostリクエストを実行してCloseableHttpResponseを取得します。

 

    1. ステータスコード、エラー情報、レスポンスHTMLなど、必要な詳細をレスポンスから取得します。

 

    最後に、apache HttpClientリソースを閉じます。

以下は、Javaプログラム自体でApache HttpClientを使用してHTTP GETおよびPOSTリクエストを実行する方法を示した最終プログラムです。

package com.scdev.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class ApacheHttpClientExample {

	private static final String USER_AGENT = "Mozilla/5.0";

	private static final String GET_URL = "https://localhost:9090/SpringMVCExample";

	private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";

	public static void main(String[] args) throws IOException {
		sendGET();
		System.out.println("GET DONE");
		sendPOST();
		System.out.println("POST DONE");
	}

	private static void sendGET() throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(GET_URL);
		httpGet.addHeader("User-Agent", USER_AGENT);
		CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

		System.out.println("GET Response Status:: "
				+ httpResponse.getStatusLine().getStatusCode());

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		// print result
		System.out.println(response.toString());
		httpClient.close();
	}

	private static void sendPOST() throws IOException {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(POST_URL);
		httpPost.addHeader("User-Agent", USER_AGENT);

		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));

		HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
		httpPost.setEntity(postParams);

		CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

		System.out.println("POST Response Status:: "
				+ httpResponse.getStatusLine().getStatusCode());

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		// print result
		System.out.println(response.toString());
		httpClient.close();

	}

}

上記のプログラムを実行すると、ブラウザで受け取ったのと同様の出力HTMLが得られます。

GET Response Status:: 200
<html><head>	<title>Home</title></head><body><h1>	Hello world!  </h1><P>  The time on the server is March 7, 2015 1:01:22 AM IST. </P></body></html>
GET DONE
POST Response Status:: 200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj Kumar</h3></body></html>
POST DONE

これがApache HttpClientの例の全てです。便利なメソッドがたくさん含まれているので、使ってみることをオススメします。より理解を深めるために、ぜひチェックしてみてください。

コメントを残す 0

Your email address will not be published. Required fields are marked *