Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setConnectTimeout() method in org.apache.hc.client5.http.config.RequestConfig

I am updating my project to use HTTP Client 5.2 version and my old code has setConnectTimeout() deprecated method.

It is now replaced with ConnectionConfig.Builder but I am not sure how to change the code

Old code:

import org.apache.hc.client5.http.config.RequestConfig;

public RequestConfig requestConfig() {
   return RequestConfig.custom()
       .setConnectionRequestTimeout(cRtimout)
       .setConnectTimeout(cTimeout)
       .setSocketTimeout(sTimout)
       .build();
}

I have referred this stackoverflow link No setSocketTimeout(timeout) method in org.apache.hc.client5.http.config.RequestConfig and changed the code as below

public RequestConfig requestConfig() {
   return RequestConfig.custom()
       .setConnectionRequestTimeout(cRtimout)
       .setResponseTimeout(sTimout) // As socketTimeout is now responseTimout
       .build();
}

This RequestConfig is passed to the below code snippet

public ClosableHttpClient httpClient(RequestConfig reqConfig,PoolingHttpClientConnectionManager poolingHttpClientConnecMgr){

  CloseableHttpClient client = HttpClients.custom().
         .setDefaultRequestConfig(reqConfig)
         .setConnectionManager(poolingHttpClientConnecMgr)
         .setRetryStrategy( // some code block here)
         .build();
}

But I am not sure how to change the code for setConnectTimout()

Can someone help on this please?

like image 858
LearnToCode Avatar asked Mar 06 '26 18:03

LearnToCode


1 Answers

There is an example of using ConnectionConfig on a Connection Manager in the migration documentation: https://hc.apache.org/httpcomponents-client-5.2.x/migration-guide/migration-to-classic.html

In this example they use PoolingHttpClientConnectionManager, created with a PoolingHttpClientConnectionManagerBuilder.

See this part in particular:

.setDefaultConnectionConfig(ConnectionConfig.custom()
              .setSocketTimeout(Timeout.ofMinutes(1))
              .setConnectTimeout(Timeout.ofMinutes(1))
              .setTimeToLive(TimeValue.ofMinutes(10))
              .build())

You can probably use another connection manager as well, supposedly it should have same setDefaultConnectionConfig method or similar on it's builder.

like image 167
mvmn Avatar answered Mar 08 '26 06:03

mvmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!