HttpClient 4.5.2版本设置连接超时时间-CloseableHttpClient设置Timeout

本文介绍如何在HttpClient 4.5版本中通过RequestConfig设置连接超时及数据获取超时时间,包括具体示例代码,并对比了4.3版本的设置方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HttpClient  4.5版本设置连接超时时间-CloseableHttpClient设置Timeout(区别于4.3.2)

 

HttpClient升级到4.5版本后,API有很多变化,HttpClient 4之后,API一直没有太稳定,我感觉4.5版本抽象后,很多API应该快稳定了。

       使用HttpClient,一般都需要设置连接超时时间和获取数据超时时间。这两个参数很重要,目的是为了防止访问其他http时,由于超时导致自己的应用受影响。

       4.5版本中,这两个参数的设置都抽象到了RequestConfig中,由相应的Builder构建,具体的例子如下:

CloseableHttpClient httpclient = HttpClients.createDefault();  
HttpGet httpGet = new HttpGet("http://stackoverflow.com/");  
RequestConfig requestConfig = RequestConfig.custom()  
        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
        .setSocketTimeout(5000).build();  
httpGet.setConfig(requestConfig);  
CloseableHttpResponse response = httpclient.execute(httpGet);  
System.out.println("得到的结果:" + response.getStatusLine());//得到请求结果  
HttpEntity entity = response.getEntity();//得到请求回来的数据

setConnectTimeout:设置连接超时时间,单位毫秒。

setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。

setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。

===========================================

昨天遇到一个问题需要设置CloseableHttpClient的超时时间,查了官方文档如下。

新建一个RequestConfig:

RequestConfig defaultRequestConfig = RequestConfig.custom()
    .setSocketTimeout(5000)
    .setConnectTimeout(5000)
    .setConnectionRequestTimeout(5000)
    .setStaleConnectionCheckEnabled(true)
    .build();

这个超时可以设置为客户端级别,作为所有请求的默认值:

CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultRequestConfig(defaultRequestConfig)
    .build();

Request不会继承客户端级别的请求配置,所以在自定义Request的时候,需要将客户端的默认配置拷贝过去:

 
HttpGet httpget = new HttpGet("http://www.apache.org/");
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
    .setProxy(new HttpHost("myotherproxy", 8080))
    .build();
httpget.setConfig(requestConfig);

 

4.3版本的超时是这样的:

public static String httpPost(String url, String jsonString) {
    // 设置HTTP请求参数
String result = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    try {
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);//设置请求超时时间 10s
StringEntity entity = new StringEntity(jsonString);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        HttpEntity resEntity = httpClient.execute(httpPost).getEntity();
        result = EntityUtils.toString(resEntity, "UTF-8");
    } catch (Exception e) {
        logger.error("http接口调用异常:url is::" + url, e);
        return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}

 

4.5.2版本是这样的:

 public static String testTimeout(String url) {

        // 设置HTTP请求参数

        String result = null;

        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);

        RequestConfig requestConfig = RequestConfig.custom()

                .setConnectTimeout(50000).setConnectionRequestTimeout(10000)

                .setSocketTimeout(50000).build();

        httpGet.setConfig(requestConfig);

        try {

            CloseableHttpResponse response = client.execute(httpGet);

            result = EntityUtils.toString(response.getEntity(), "UTF-8");

        } catch (ClientProtocolException e) {

            logger.error("http接口调用异常:url is::" + url, e);

            return null;

        } catch (Exception e) {

            logger.error("http接口调用异常:url is::" + url, e);

            return null;

        } finally {

            try {

                client.close();

            } catch (IOException e) {

                logger.error("http接口调用异常:url is::" + url, e);

            }

        }

        return result;

    }

 

 

<think>我们正在使用Apache HttpClient,并且需要为不同的请求设置不同的连接超时时间。根据引用[2]和引用[3],我们知道可以通过RequestConfig设置超时时间连接超时和读取超时)。但是,HttpClient通常是通过一个共享的实例来发送多个请求的,而默认的RequestConfig是在创建HttpClient设置的(作为默认配置)。然而,我们也可以在每个请求上覆盖这个默认配置,即为每个请求设置独立的RequestConfig。步骤:1.创建HttpClient实例时,可以设置一个默认的RequestConfig(可选,如果有些请求没有特别设置,则使用默认)。2.对于需要特殊超时时间的请求,我们可以构建一个特定的RequestConfig,并在执行请求时将其设置到HttpRequest(如HttpGet或HttpPost)中。示例代码:首先,创建一个默认配置的HttpClient(可选): ```java//默认的配置,比如连接超时和读取超时都是5RequestConfigdefaultConfig= RequestConfig.custom().setConnectTimeout(5000)//连接超时时间,单位毫秒.setSocketTimeout(5000)//读取超时(等待数据超时时间,单位毫秒.build();CloseableHttpClienthttpClient= HttpClients.custom().setDefaultRequestConfig(defaultConfig).build(); ```然后,对于需要不同超时时间的请求,我们可以为这个请求单独创建一个RequestConfig,并在请求对象上设置:```java//创建一个特殊的请求配置,连接超时10秒,读取超时20秒RequestConfig specialConfig =RequestConfig.copy(defaultConfig).setConnectTimeout(10000).setSocketTimeout(20000).build();//创建HttpGet请求HttpGethttpGet= newHttpGet("http://example.com");//将特殊的配置设置到这个请求上httpGet.setConfig(specialConfig);//执行请求CloseableHttpResponse response= httpClient.execute(httpGet); ```这样,这个特定的请求就会使用它自己的超时配置,而其他没有设置Config的请求则会使用默认配置。注意:引用[2]中提到,HttpContext中的RequestConfig配置值默认是null,所以我们需要在请求中明确设置。而上面的方式就是在请求对象上设置。另外,如果不想设置默认配置,那么每个请求都必须设置自己的配置,否则会使用系统默认(可能没有超时限制,不推荐)。所以建议设置一个合理的默认配置,然后针对特殊请求覆盖。总结:通过为每个请求设置不同的RequestConfig对象,可以实现不同的超时时间配置。相关问题:1.如何在HttpClient中同时设置连接超时和读取超时2.如何为HttpClient设置全局默认的超时时间?3.如果某个请求没有设置RequestConfig,会使用什么配置?4.除了超时时间RequestConfig还可以配置哪些参数?</think>### 为不同请求配置不同超时时间的解决方案 在 Apache HttpClient 中,可通过以下方法为不同请求设置独立的连接超时时间: #### 1. **为每个请求创建独立配置** ```java // 创建基础 HttpClient 实例(不设置默认配置) CloseableHttpClient httpClient = HttpClients.createDefault(); // 请求1:短超时配置(2秒) RequestConfig shortTimeoutConfig = RequestConfig.custom() .setConnectTimeout(2000) // 连接超时 .setSocketTimeout(2000) // 数据传输超时 .build(); // 请求2:长超时配置(10秒) RequestConfig longTimeoutConfig = RequestConfig.custom() .setConnectTimeout(10000) .setSocketTimeout(10000) .build(); // 执行请求1 HttpGet request1 = new HttpGet("https://fast-api.com"); request1.setConfig(shortTimeoutConfig); // ⭐关键:绑定独立配置 try (CloseableHttpResponse response = httpClient.execute(request1)) { // 处理响应 } // 执行请求2 HttpGet request2 = new HttpGet("https://slow-api.com"); request2.setConfig(longTimeoutConfig); // ⭐绑定另一配置 try (CloseableHttpResponse response = httpClient.execute(request2)) { // 处理响应 } ``` #### 2. **使用配置工厂(推荐复用场景)** ```java // 创建可复用的配置工厂 Map<String, RequestConfig> configFactory = new HashMap<>(); configFactory.put("SHORT_TIMEOUT", RequestConfig.custom() .setConnectTimeout(2000).setSocketTimeout(2000).build()); configFactory.put("LONG_TIMEOUT", RequestConfig.custom() .setConnectTimeout(10000).setSocketTimeout(10000).build()); // 按需获取配置 HttpGet request = new HttpGet("https://api.example.com"); request.setConfig(configFactory.get("LONG_TIMEOUT")); // 动态选择配置 httpClient.execute(request); ``` ### 关键说明: 1. **配置优先级** - 请求级配置 > 客户端默认配置 - 通过 `request.setConfig()` 设置的配置会覆盖 HttpClient 的默认配置[^2][^3] 2. **核心参数** - `setConnectTimeout()`:建立 TCP 连接的最大等待时间 - `setSocketTimeout()`:两次数据包之间的最大等待时间[^1][^3] 3. **线程安全性** - `RequestConfig` 是线程安全的,可在多线程环境复用 - 每个 `HttpRequest` 对象应独立设置配置 > **最佳实践**:对于需要不同超时的并发请求,建议结合线程池管理,每个线程使用独立的请求配置[^2]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值