In this post under JAX-RS I will show with example how to set cookies, when making REST api calls, using JAX-RS client api.
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 Example10 {
10 public static void main(String[] args) {
11 Client client = ClientBuilder.newClient();
12 WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users/2");
13 Invocation.Builder builder = webTarget.request();
14 builder = builder.cookie("cookieName1","cookieValue1");
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 at line 13, we are creating an instance of “Invocation.Builder” class named “builder”.
At line 14, we are setting a cookie by calling “cookie” method on the “builder” instance and passing the cookie key and value as an argument.
Remaining code is same as in previous posts.
In this way we can set the cookies using JAX-RS client api