CloseableHttpClient如何设置超市时间
时间: 2023-12-19 13:30:07 浏览: 110
CloseableHttpClient可以通过设置连接超时时间、请求超时时间和响应超时时间来控制超时。具体设置方法如下:
```java
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpGet请求对象
HttpGet httpGet = new HttpGet("http://www.example.com");
// 设置连接超时时间(单位毫秒)
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.build();
httpGet.setConfig(requestConfig);
// 设置请求超时时间(单位毫秒)
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.build();
httpGet.setConfig(requestConfig);
// 设置响应超时时间(单位毫秒)
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5000)
.build();
httpGet.setConfig(requestConfig);
// 执行请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
```
以上代码中,通过RequestConfig对象的setConnectTimeout()、setSocketTimeout()和setConnectionRequestTimeout()方法设置连接超时时间、请求超时时间和响应超时时间,单位均为毫秒。然后将RequestConfig对象设置到HttpGet请求对象中,最后通过CloseableHttpClient对象的execute()方法执行请求并获取响应。
阅读全文
相关推荐

















