1.概述

在本教程中,我们将说明Apache最常见的用例httpasyncclient- 从基本用法,如何拨弄, 如何使用SSL证书最后 - 如何认证使用异步客户机。

2.简单的例子

首先,让我们看看如何使用httpasyncclient在一个简单的例子中 - 发送GET请求:

@Test public void whenUseHttpAsyncClient_thenCorrect() throws Exception {CloseableHttpAsyncClient client = httpasyncclient . createdefault ();client.start ();HttpGet request = new HttpGet("http://www.google.com");未来未来= client.execute(请求,null);HttpResponse response = future.get();为了(response.getStatusLine () .getStatusCode(),等于(200);client.close ();}

说明如何我们需要开始在使用异步客户端之前;没有那个,我们会得到以下例外:

java.lang.illegalstateException:无法执行请求;I / O反应堆状态:O.a.h.u.asserts.Check(Asserts.java:46)处于O.a.h.i.n.c.closeableHttpasyncClientBase。Ensurerunning(Closeablehttpasyncclientbase.java:90)

3.多线程httpasyncclient

现在 - 让我们看看如何使用httpasyncclient同时执行多个请求。

在以下示例中 - 我们将三个GET请求发送到三个不同的主机httpasyncclientpoolingnhttpclientConnectionManager.

@Test public void whenusemultiplehttpasyncclient_thecorrect () throws Exception {ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);CloseableHttpAsyncClient client = httpasyncclient .custom().setConnectionManager(cm).build();client.start ();String [] (= {" http://www.google.com/ ", " http://www.apache.org/ ", " http://www.bing.com/ "};GetThread[] threads = new GetThread[together .length];for (int i = 0;我< threads.length;/ /获取[i] / /获取[i] / /获取[i]线程[i] = new GetThread(客户端,请求); } for (GetThread thread : threads) { thread.start(); } for (GetThread thread : threads) { thread.join(); } }

这是我们的Getthread.实施处理响应:

static class GetThread extends Thread {private CloseableHttpAsyncClient client;私人HttpContext上下文;私人HttpGet请求;public GetThread(CloseableHttpAsyncClient客户端,HttpGet req){这个。客户=客户;上下文= HttpClientContext.create ();这一点。请求=要求;} @Override public void run() {try {Future Future = client。执行(请求、上下文无效);HttpResponse response = future.get();为了(response.getStatusLine () .getStatusCode(),等于(200); } catch (Exception ex) { System.out.println(ex.getLocalizedMessage()); } } }

4.代理httpasyncclient

接下来-让我们看看如何设置和使用a代理人httpasyncclient

在以下示例中 - 我们发送一个HTTP通过代理获取请求

@Test public void whenUseProxyWithHttpClient_thenCorrect() throws Exception {CloseableHttpAsyncClient client = httpasyncclient . 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(配置);未来未来= client.execute(请求,null);HttpResponse response = future.get();为了(response.getStatusLine () .getStatusCode(),等于(200);client.close (); }

5.SSL证书与httpasyncclient

现在,我们来看看如何使用aSSL证书httpasyncclient

在以下示例中 - 我们配置httpasyncclient接受所有证书

@test public void whenusesslwithhttpasyncclient_thencorrect()抛出异常{truststrategy acceptingtruststrategy = new truststrategy(){public boolean istrusted(x509certificate []证书,String authtype){return true;}};sslcontext sslcontext = sslcontexts.custom().loadtrustMaterial(null,AcceptingTruststrategy).build();closeablehttpasyncclient client = httpasyncclients.custom().setslhostnameverifier(sslconnectionsocketfactory.allow_all_hostname_verifier).setsslcontext(sslcontext).build();client.start ();httpget请求= new httpget(“https://mms.nw.ru/”);未来未来= client.execute(请求,null);HttpResponse response = future.get();为了(response.getStatusLine () .getStatusCode(),等于(200);client.close (); }

6.饼干httpasyncclient

接下来,让我们看看如何使用cookiehttpasyncclient

在以下示例中 - 我们在发送请求之前设置cookie值

@test public void whenUsecookieswithhttpasyncclient_thengorrect()抛出异常{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请求= new httpget(“http://www.github.com”);httpcontext localcontext = new basichttpcontext();localContext.setAttribute(HttpClientContext.Cookie_Store,Cookiestore); Future 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()抛出异常{credentialsprovider提供程序= new basiccredentialsprovider();Usernamepasswordcredentials Creds = New UsernamePasswordCredentials(“用户”,“通过”);Provider.SetCredentials(authscope.any,Creds);closeablehttpasyncclient client = httpasyncclients.custom()。setDefaultCredentialSprovider(提供程序).build();client.start ();httpget请求=新的httpget(“http:// localhost:8080”);未来未来= client.execute(请求,null);HttpResponse response = future.get();为了(response.getStatusLine () .getStatusCode(),等于(200);client.close (); }

结论

在本文中,我们说明了异步Apache HTTP客户端的各种用例。

所有这些示例和代码片段的实现可以找到我的github项目- 这是一个基于Eclipse的项目,因此应该易于导入和运行。

通用底部

使用Spring 5和Spring Boot 2开始,通过学习春天课程:

>>查看课程
本文评论关闭!