簡(jiǎn)述
本文介紹Apache HttpAsyncClient的最常見(jiàn)用例,從基本用法到如何設(shè)置代理谁帕,如何使用SSL證書(shū)以及最后如何使用異步客戶端進(jìn)行身份驗(yàn)證辩蛋。
簡(jiǎn)單Demo
首先技健,讓我們看一下如何在一個(gè)簡(jiǎn)單的例子中使用HttpAsyncClient骄呼,發(fā)送一個(gè)GET請(qǐng)求:
@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();
}
注意我們?cè)谑褂弥靶枰獑?dòng)HttpAsyncClients
; 沒(méi)有它,我們會(huì)得到以下異常:
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進(jìn)行多線程處理
現(xiàn)在琼富,讓我們看看如何使用HttpAsyncClient同時(shí)執(zhí)行多個(gè)請(qǐng)求仪吧。
在以下示例中,我們使用HttpAsyncClient和PoolingNHttpClientConnectionManager向三個(gè)不同的主機(jī)發(fā)送三個(gè)GET請(qǐng)求:
@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實(shí)現(xiàn)來(lái)處理響應(yīng):
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的代理
接下來(lái)鞠眉,讓我們來(lái)看看如何設(shè)置和使用代理服務(wù)器與HttpAsyncClient薯鼠。
在以下示例中,我們通過(guò)代理發(fā)送HTTP GET請(qǐng)求:
@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證書(shū)
現(xiàn)在械蹋,讓我們來(lái)看看如何使用SSL證書(shū)與HttpAsyncClient出皇。
在以下示例中, 我們將HttpAsyncClient配置為接受所有證書(shū):
@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
接下來(lái)朝蜘,讓我們看看如何在HttpAsyncClient中使用cookie 。
在以下示例中涩金,我們?cè)诎l(fā)送請(qǐng)求之前設(shè)置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進(jìn)行身份驗(yàn)證
接下來(lái)谱醇,讓我們看看如何使用HttpAsyncClient進(jìn)行身份驗(yàn)證暇仲。
在以下示例中,我們使用CredentialsProvider通過(guò)基本身份驗(yàn)證訪問(wèn)主機(jī):
@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();
}
結(jié)論
本文介紹的內(nèi)容希望你對(duì)HttpAsyncClient有深刻的了解