JAX-RS Client Connect Timeout

In this post under JAX-RS client, I will show with example how to set connect timeout.

Below is the complete code for your reference

Main Class


1  package defaultPackage;
2  
3  import java.util.concurrent.TimeUnit;
4  
5  import jakarta.ws.rs.client.Client;
6  import jakarta.ws.rs.client.ClientBuilder;
7  import jakarta.ws.rs.client.Invocation;
8  import jakarta.ws.rs.client.WebTarget;
9  import jakarta.ws.rs.core.Response;
10 
11 public class Example14 {
12     public static void main(String[] args) {
13         ClientBuilder clientBuilder = ClientBuilder.newBuilder();
14         clientBuilder.connectTimeout(1, TimeUnit.MILLISECONDS);
15         Client client = clientBuilder.build();
16         try {
17             WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users/2");
18             Invocation.Builder builder = webTarget.request();
19             Invocation invocation = builder.buildGet();
20             Response response = invocation.invoke();
21             if(response.getStatus() == 200) {
22                 System.out.println("Successful");
23                 String result = response.readEntity(String.class);
24                 System.out.println(result);
25             } else {
26                 System.out.println("Failed");
27             }
28         } finally {
29             client.close();
30         }
31     }
32 }

In the above code, at line 14, we call “connectTimeout” method on the “ClientBuilder” instance and pass the duration.

In this way we can set the connect timeout.

Leave a Reply