javaapache-httpclient-5.x

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?


Solution

  • 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.