使用httpClient请求的时候 connectTimeOut和readTimeOut应该设置到什么位置才生效?
场景1:没有httpclient池子的情况
public void test(){
HttpGet get = new HttpGet("https://www.baidu.com");
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(1000)
.setConnectTimeout(1000)
.setConnectionRequestTimeout(1000)
.build();
get.setConfig(config);
try {
httpClient.execute(get);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
解释:以上代码是发起一个get请求,需要将readTimeOut、connectTimeOut和ConnectionRequestTimeout设置到HttpGet/HttpPost/HttpPut…对象上,设置到这里是生效的。
场景2:使用带着池子的httpclient对象
public void test(){
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(10);
connManager.setDefaultMaxPerRoute(10);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(1000)
.setConnectTimeout(1000)
.setConnectionRequestTimeout(3000)
.build();
HttpGet get = new HttpGet("https://www.baidu.com");
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(requestConfig).build();
try {
CloseableHttpResponse response = httpClient.execute(get);
httpClient.close();
System.out.println(response);
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
这种场景是将三个超时时间设置到了httpclient对象上,经过测试之后发现,设置到httpclient对象上的ConnectionRequestTimeout超时时间是不生效的,且会默认走-1.
总结:设置请求的超时时间要设置到HttpGet/HttpPost/HttpPut对象上。
题外知识点
1、实现了AutoCloseable接口的类在使用过程中要关闭资源,避免资源泄露,如HttpClient、HttpResponse对象。
2、try-with-resource 写法可以在try块执行完时关闭资源:
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建 HTTP GET 请求
HttpGet httpGet = new HttpGet("https://www.baidu.com");
// 配置请求参数
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(1000) // 设置 socket 超时时间
.setConnectTimeout(1000) // 设置连接超时时间
.setConnectionRequestTimeout(1000) // 设置从连接池获取连接的超时时间
.build();
httpGet.setConfig(config);
// 执行请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
// 处理响应
// 例如,打印响应内容
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
} catch (IOException e) {
// 处理响应处理过程中的异常
e.printStackTrace();
}
} catch (IOException e) {
// 处理 HttpClient 创建或执行过程中的异常
e.printStackTrace();
}
}
}