Till now in all my previous posts under JAX-RS client, the examples I showed made synchronous call to REST resource using JAX-RS client api.
In this post under JAX-RS client, I will show with example how to make an asynchronous call to REST resource using JAX-RS client api.
Below is the complete code for your reference.
Main class
1 package defaultPackage;
2
3 import java.util.concurrent.ExecutionException;
4 import java.util.concurrent.Future;
5
6 import jakarta.ws.rs.client.Client;
7 import jakarta.ws.rs.client.ClientBuilder;
8 import jakarta.ws.rs.client.Invocation;
9 import jakarta.ws.rs.client.WebTarget;
10 import jakarta.ws.rs.core.Response;
11
12 public class Example11 {
13 public static void main(String[] args) throws InterruptedException, ExecutionException {
14 Client client = ClientBuilder.newClient();
15 WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users/2");
16 Invocation.Builder builder = webTarget.request();
17 Invocation invocation = builder.buildGet();
18 Future<Response> futureResponse = invocation.submit();
19 while(!futureResponse.isDone()) {
20 System.out.append('*');
21 Thread.sleep(100);
22 };
23 System.out.append("\r\n");
24 System.out.append("Successful");
25 String result = futureResponse.get().readEntity(String.class);
26 System.out.append(result);
27 client.close();
28 }
29 }
Till now whenever we made a REST call, we used the below method from “Invocation” instance to submit the http request, as shown below
invocation.invoke();
The above code snippet will make an synchronous call to REST resource.
We will replace this, with the method “submit” on “Invocation” instance. Refer to line 18 in the above code.
This “submit” method will return a “Future” instance, which we will use to query whether the REST api call is done or not, as shown in the “while” condition at line 19.
The while loop will run untill the asynchronous call is done.
Once it is done we get the data from “Future” instance as shown at line 25.
In this way we can make asynchronous calls using JAX-RS client api.
Below is the output
Output
***
Successful{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
}