Java HttpClientUtil Read timed out executing GET 错误解决方法

在使用 HttpClientUtil 发送 GET 请求时,可能会遇到 Read timed out executing GET 的错误。本文将介绍几种常见的解决方法。

问题描述

当使用 HttpClientUtil 发送 GET 请求时,如果目标服务器响应时间过长,或者网络连接不稳定,就可能会出现 Read timed out executing GET 错误。

解决办法

1. 增加请求超时时间

可以通过设置 setConnectTimeoutsetSocketTimeout 两个参数来增加请求超时时间。例如:

CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(5000) // 设置连接超时时间
        .setSocketTimeout(5000) // 设置读取超时时间
        .build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpGet);

2. 禁用重试机制

HttpClient 默认会进行重试,可以通过设置重试次数为 0 来禁用重试机制。例如:

CloseableHttpClient httpClient = HttpClients.custom()
        .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) // 禁用重试机制
        .build();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);

3. 增加连接池

可以通过增加连接池来提高请求的效率和稳定性。例如:

PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(100); // 设置最大连接数
connectionManager.setDefaultMaxPerRoute(20); // 设置每个路由的最大连接数
CloseableHttpClient httpClient = HttpClients.custom()
        .setConnectionManager(connectionManager) // 设置连接池
        .build();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);

总结

以上是解决 HttpClientUtil Read timed out executing GET 错误的三种方法,可以根据自己的需求选择相应的解决方案。同时,建议在使用 HttpClient 发送请求时,根据具体情况设置合适的超时时间和连接池大小,以保证请求的稳定性和效率。

Java HttpClientUtil Read timed out executing GET 错误解决方法

原文地址: https://www.cveoy.top/t/topic/n5Os 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录