In this post under JAX-RS Client, I will show with example how to make a REST api call to a resource and send query parameters.
Below is the complete code for your reference.
Main Class
1 package defaultPackage;
2
3 import jakarta.ws.rs.client.Client;
4 import jakarta.ws.rs.client.ClientBuilder;
5 import jakarta.ws.rs.client.Invocation;
6 import jakarta.ws.rs.client.WebTarget;
7 import jakarta.ws.rs.core.Response;
8
9 public class Example6 {
10 public static void main(String[] args) {
11 Client client = ClientBuilder.newClient();
12 WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users");
13 webTarget = webTarget.queryParam("id", "1");
14 Invocation.Builder builder = webTarget.request();
15 Invocation invocation = builder.buildGet();
16 Response response = invocation.invoke();
17 if(response.getStatus() == 200) {
18 System.out.println("Successful");
19 String result = response.readEntity(String.class);
20 System.out.println(result);
21 } else {
22 System.out.println("Failed");
23 }
24 client.close();
25 }
26 }
In the above code, at line 12, we are creating an instance of “WebTarget” class.
At line 13, we call “queryParam” method on “WebTarget” instance to pass the query parameters.
The “queryParam” method takes two arguments. First is query parameter name and second is query parameter value.
At line 14, we create an instance of “Invocation.Builder” class from “WebTarget” instance.
At line 15, from the instance of “Invocation.Builder” class, we create an instance of “Invocation” object.
This “Invocation” object will execute http GET call on the url with the specified query parameters when “invoke” is called.
At line 16, we execute the HTTP Get call by calling “invoke” method on the “Invocation” object.
This will return a “Response” object.
Based on status of “Response” object appropriate message will be displayed in the console.
In this way we can call a REST resource and also pass along query parameters.