HttpAsyncClientチュートリアル
1概要
このチュートリアルでは、Apache
HttpAsyncClient
の最も一般的なユースケース – 基本的な使い方から、プロキシの設定方法、SSL証明書の使い方、そして最後に非同期クライアントでの認証方法までを説明します。 。
2簡単な例
まず、簡単な例で
HttpAsyncClient
を使用する方法を見てみましょう – GETリクエストを送信します。
@Test
public void whenUseHttpAsyncClient__thenCorrect() throws Exception {
CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
HttpGet request = new HttpGet("http://www.google.com");
Future<HttpResponse> future = client.execute(request, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
非同期クライアントを使う前に、どのように非同期クライアントを起動する必要があるかに注意してください。それがなければ、次の例外が発生します。
java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: INACTIVE
at o.a.h.u.Asserts.check(Asserts.java:46)
at o.a.h.i.n.c.CloseableHttpAsyncClientBase.
ensureRunning(CloseableHttpAsyncClientBase.java:90)
3
HttpAsyncClient
によるマルチスレッド
それでは、
HttpAsyncClient
を使用して複数のリクエストを同時に実行する方法を見てみましょう。
次の例では、
HttpAsyncClient
と
PoolingNHttpClientConnectionManager
を使用して、3つの異なるホストに3つのGETリクエストを送信します。
@Test
public void whenUseMultipleHttpAsyncClient__thenCorrect() throws Exception {
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
PoolingNHttpClientConnectionManager cm =
new PoolingNHttpClientConnectionManager(ioReactor);
CloseableHttpAsyncClient client =
HttpAsyncClients.custom().setConnectionManager(cm).build();
client.start();
String[]toGet = {
"http://www.google.com/",
"http://www.apache.org/",
"http://www.bing.com/"
};
GetThread[]threads = new GetThread[toGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet request = new HttpGet(toGet[i]);
threads[i]= new GetThread(client, request);
}
for (GetThread thread : threads) {
thread.start();
}
for (GetThread thread : threads) {
thread.join();
}
}
応答を処理するための
GetThread
実装は次のとおりです。
static class GetThread extends Thread {
private CloseableHttpAsyncClient client;
private HttpContext context;
private HttpGet request;
public GetThread(CloseableHttpAsyncClient client,HttpGet req){
this.client = client;
context = HttpClientContext.create();
this.request = req;
}
@Override
public void run() {
try {
Future<HttpResponse> future = client.execute(request, context, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
}
}
4
HttpAsyncClient
によるプロキシ
次に、
HttpAsyncClient
を使って
proxy
を設定して使用する方法を見てみましょう。
次の例では、プロキシ
を介してHTTP
GETリクエストを送信します。
@Test
public void whenUseProxyWithHttpClient__thenCorrect() throws Exception {
CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
HttpHost proxy = new HttpHost("74.50.126.248", 3127);
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet request = new HttpGet("https://issues.apache.org/");
request.setConfig(config);
Future<HttpResponse> future = client.execute(request, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
5
HttpAsyncClient
を使用したSSL証明書
それでは、
HttpAsyncClient
で
SSL証明書
を使用する方法を見てみましょう。
次の例では、すべての証明書を受け入れるように
HttpAsyncClient
を設定しています。
@Test
public void whenUseSSLWithHttpAsyncClient__thenCorrect() throws Exception {
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[]certificate, String authType) {
return true;
}
};
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy).build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW__ALL__HOSTNAME__VERIFIER)
.setSSLContext(sslContext).build();
client.start();
HttpGet request = new HttpGet("https://mms.nw.ru/");
Future<HttpResponse> future = client.execute(request, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
6.
HttpAsyncClient
を使用したクッキー
次に、
HttpAsyncClient
でクッキーを使用する方法を見てみましょう。
次の例では、リクエストを送信する前にcookie値を設定しています。
@Test
public void whenUseCookiesWithHttpAsyncClient__thenCorrect() throws Exception {
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
HttpGet request = new HttpGet("http://www.github.com");
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE__STORE, cookieStore);
Future<HttpResponse> future = client.execute(request, localContext, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
7. HttpAsyncClient
による認証
次に、
HttpAsyncClient
による認証の使い方を見てみましょう。
次の例では、
CredentialsProvider
を使用して基本認証を通じてホストにアクセスします。
@Test
public void whenUseAuthenticationWithHttpAsyncClient__thenCorrect() throws Exception {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "pass");
provider.setCredentials(AuthScope.ANY, creds);
CloseableHttpAsyncClient client =
HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
client.start();
HttpGet request = new HttpGet("http://localhost:8080");
Future<HttpResponse> future = client.execute(request, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
8結論
この記事では、非同期Apache Httpクライアントのさまざまなユースケースを説明しました。
これらすべての例とコードスニペットの実装はhttps://github.com/eugenp/tutorials/tree/master/httpclient#readme[my githubプロジェクト]にあります。そのままインポートして実行するのは簡単です。