httpclient发送https请求 并且配置连接池
时间: 2023-11-23 14:43:40 浏览: 150
使用HttpClient发送HTTPS请求并配置连接池,可以按照以下步骤进行:
1. 创建SSLContext对象,用于HTTPS连接的安全认证。
```java
SSLContext sslContext = SSLContexts.createSystemDefault();
```
2. 创建ConnectionSocketFactory对象,用于连接池中的连接创建。
```java
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
```
3. 创建HttpClientConnectionManager对象,用于管理连接池中的连接。
```java
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(Arrays.asList(sslConnectionSocketFactory));
poolingHttpClientConnectionManager.setMaxTotal(200);//设置最大连接数
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100);//设置每个路由最大连接数
```
4. 创建HttpClient对象,并设置连接池管理器。
```java
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(poolingHttpClientConnectionManager)
.build();
```
5. 创建HttpPost对象,设置请求参数,并执行请求。
```java
HttpPost httpPost = new HttpPost("https://example.com/path");
httpPost.setEntity(new StringEntity("Hello, world!"));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
```
完整的示例代码如下:
```java
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import javax.net.ssl.SSLContext;
import java.util.Arrays;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) throws IOException {
SSLContext sslContext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(Arrays.asList(sslConnectionSocketFactory));
poolingHttpClientConnectionManager.setMaxTotal(200);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(poolingHttpClientConnectionManager)
.build();
HttpPost httpPost = new HttpPost("https://example.com/path");
httpPost.setEntity(new StringEntity("Hello, world!"));
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.getStatusLine().getStatusCode());
httpResponse.close();
httpClient.close();
}
}
```
阅读全文