使用PoolingHttpClientConnectionManager可以创建一个具有连接池功能的HttpClient实例。下面是一个示例代码:
java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
// 创建连接池管理器
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
// 设置最大连接数
connectionManager.setMaxTotal(50);
// 设置每个路由的最大连接数
connectionManager.setDefaultMaxPerRoute(10);
// 创建HttpClient对象,使用连接池管理连接
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.build();
try {
// 创建HttpGet请求
HttpGet httpGet = new HttpGet("https://api.example.com");
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 处理响应内容
if (entity != null) {
String responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
}
} finally {
// 关闭响应
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭HttpClient连接
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在这个示例中,使用PoolingHttpClientConnectionManager设置了连接池的最大连接数和每个路由的最大连接数。然后,通过HttpClients.custom().setConnectionManager(connectionManager).build()创建了一个带有连接池功能的HttpClient实例。可以根据需要进行进一步的配置和定制化。