简述
本文介绍Apache HttpAsyncClient的最常见用例,从基本用法到如何设置代理,如何使用SSL证书以及最后如何使用异步客户端进行身份验证。
简单Demo
首先,让我们看一下如何在一个简单的例子中使用HttpAsyncClient,发送一个GET请求:
@Test
public void test() throws Exception {
CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
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();
}
注意我们在使用之前需要启动HttpAsyncClients
; 没有它,我们会得到以下异常:
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)
使用HttpAsyncClient进行多线程处理
现在,让我们看看如何使用HttpAsyncClient同时执行多个请求。
在以下示例中,我们使用HttpAsyncClient和PoolingNHttpClientConnectionManager向三个不同的主机发送三个GET请求:
@Test
public void test() throws Exception {
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
PoolingNHttpClientConnectionManager cm =
new PoolingNHttpClientConnectionManager(ioReactor);
CloseableHttpAsyncClient client =
HttpAsyncClients.custom().setConnectionManager(cm).build();
client.start();
String[] toGet = {
"192.168.0.101:8080",
"192.168.0.102:8080",
"192.168.0.103:8080"
};
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());
}
}
}
使用HttpAsyncClient的代理
接下来,让我们来看看如何设置和使用代理服务器与HttpAsyncClient。
在以下示例中,我们通过代理发送HTTP GET请求:
@Test
public void test() 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("http://192.168.0.101");
request.setConfig(config);
Future<HttpResponse> future = client.execute(request, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
使用HttpAsyncClient的SSL证书
现在,让我们来看看如何使用SSL证书与HttpAsyncClient。
在以下示例中, 我们将HttpAsyncClient配置为接受所有证书:
@Test
public void test() 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("");
Future<HttpResponse> future = client.execute(request, null);
HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
使用HttpAsyncClient的Cookie
接下来,让我们看看如何在HttpAsyncClient中使用cookie 。
在以下示例中,我们在发送请求之前设置cookie值:
@Test
public void test() throws Exception {
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".william.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
HttpGet request = new HttpGet("http://localhost:8080");
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();
}
使用HttpAsyncClient进行身份验证
接下来,让我们看看如何使用HttpAsyncClient进行身份验证。
在以下示例中,我们使用CredentialsProvider通过基本身份验证访问主机:
@Test
public void test() 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();
}
结论
本文介绍的内容希望你对HttpAsyncClient有深刻的了解
网友评论