简述
本文介绍HttpClient的连接管理,主要介绍使用BasichttpClientConnectionManager和PoolingHttpClientConnectionManager来实现强制安全,协议兼容和有效使用HTTP连接。
用于单线程连接的BasicHttpClientConnectionManager
自HttpClient 4.3.3起,BasicHttpClientConnectionManager可用作HTTP连接管理器的最简单实现。它用于创建和管理一次只能由一个线程使用的单个连接。
获取低级别连接的连接请求(HttpClientConnection)
BasicHttpClientConnectionManager connManager
= new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("http://localhost:8080", 80));
ConnectionRequest connRequest = connManager.requestConnection(route, null);
该requestConnection方法
从connManager得到的连接池的特定路线来连接。该路线参数指定的“代理跳”到目标主机或目标主机本身的路由。
可以直接使用HttpClientConnection执行请求,但请记住,这种低级方法很冗长且难以管理。低级连接对于socket和http(如超时和目标主机信息)很有用,但对于标准执行,HttpClient是一个更容易使用的API。
使用PoolingHttpClientConnectionManager获取和管理多线程连接池
该PoolingHttpClientConnectionManager将创建并管理我们使用的每个路线或目标主机的连接池。首先,让我们看看如何在一个简单的HttpClient上设置这个连接管理器:
在HttpClient上设置PoolingHttpClientConnectionManager
HttpClientConnectionManager poolingConnManager
= new PoolingHttpClientConnectionManager();
CloseableHttpClient client
= HttpClients.custom().setConnectionManager(poolingConnManager)
.build();
client.execute(new HttpGet("/"));
assertTrue(poolingConnManager.getTotalStats().getLeased() == 1);
接下来,让我们看看两个不同线程中运行的两个HttpClient如何使用相同的ConnectionManager:
使用两个HttpClient连接到每个目标主机
HttpGet get1 = new HttpGet("");
HttpGet get2 = new HttpGet("");
PoolingHttpClientConnectionManager connManager
= new PoolingHttpClientConnectionManager();
CloseableHttpClient client1
= HttpClients.custom().setConnectionManager(connManager).build();
CloseableHttpClient client2
= HttpClients.custom().setConnectionManager(connManager).build();
MultiHttpClientConnThread thread1
= new MultiHttpClientConnThread(client1, get1);
MultiHttpClientConnThread thread2
= new MultiHttpClientConnThread(client2, get2);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
请注意,我们使用的是一个非常简单的自定义线程实现,这里是:
自定义线程执行 GET请求
public class MultiHttpClientConnThread extends Thread {
private CloseableHttpClient client;
private HttpGet get;
// standard c