In this post under JAX-RS Client, I will show with example how to set headers when sending the REST request.
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 Example8 {
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.header("Content-Type", "application/json");
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 14, we are setting header “Content-Type” to “application/json” by calling “header” method on “Invocation.Builder” instance.
In this way we can set headers before sending REST requests to the server.