HttpClient Object in Java 11 OpenJDK

177 Views Asked by At

I'm using Java 11 HttpClient to send request to a remote server.

I wanted to know if there is a difference on the HttpClient object when creating object in below 2 different ways

HttpClient client = HttpClient.newHttpClient();

vs

HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).
    .connectTimeout(Duration.ofMillis(2000))
    .build();

For Starters,

  1. There seems to be no provision to set connectTimeout when creating object using HttpClient.newHttpClient()

  2. Also, as per this question, it appears a default connection pool (UNLIMITED connections) is created with keepalive.timeout=1200 seconds only when the HTTPCLient object is created using HttpClient.newHttpClient().

Does this not happen when it is created using the following?

HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).
    .connectTimeout(Duration.ofMillis(connectionTimeout))
    .build()

I want to leverage automatic connection pool creation of Java 11 HTTPClient with my custom keepalive.timeout=120 sec and still be able to also set connectTimeout value.

Please advise, TIA.

2

There are 2 best solutions below

0
Eran On

HttpClient.newHttpClient() is equivalent to HttpClient.newBuilder().build(). This means that it creates an HttpClient with default settings.

Therefore, if you need non default settings, you should use

HttpClient client = HttpClient.newBuilder()
                              .version(HttpClient.Version.HTTP_1_1). 
                              .connectTimeout(Duration.ofMillis(2000)) 
                              .build();

As for the keep alive property, as mentioned in the referenced question, you can change the default to 2 minutes with

-Djdk.httpclient.keepalive.timeout=120

This will affect all HttpClient instances, regardless of whether you create them with HttpClient.newBuilder() or with HttpClient.newHttpClient().

0
Kumar Bhaskar On

You Can set your Keep-Alive time by using

-Djdk.httpclient.keepalive.timeout=120

Or making a Static Block and set System Property

static{
       System.setProperty("jdk.httpclient.keepalive.timeout","120");
   }