CloseableHttpClient 如何设置参数
时间: 2023-10-14 07:31:00 浏览: 110
CloseableHttpClient调用三方HTTP接口,带有FILE文件类型参数
CloseableHttpClient 是 Apache HttpComponents 客户端库中的一个类,可以用于向 HTTP 服务器发起请求。它可以通过设置 HttpClientBuilder 对象的参数来配置。以下是一些常见的参数设置方式:
1. 设置连接超时时间(单位:毫秒):
```
int timeout = 5000;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.build();
```
2. 设置代理服务器:
```
HttpHost proxy = new HttpHost("proxy.example.com", 8080, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.build();
```
3. 添加请求头:
```
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultHeaders(Arrays.asList(
new BasicHeader("Accept-Encoding", "gzip, deflate"),
new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")))
.build();
```
4. 开启重定向:
```
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
```
以上是一些常见的参数设置方式,你可以根据自己的需求进行设置。
阅读全文