Setting ACCEPT header using JAX-RS client

In this post under JAX-RS I will show with example how to set ACCEPT header 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 java.util.Locale;
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 Example9 {
12     public static void main(String[] args) {
13         Client client = ClientBuilder.newClient();
14         WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users/2");
15         Invocation.Builder builder = webTarget.request();
16         builder = builder.acceptLanguage(Locale.ENGLISH);
17         Invocation invocation = builder.buildGet();
18         Response response = invocation.invoke();
19         if(response.getStatus() == 200) {
20             System.out.println("Successful");
21             String result = response.readEntity(String.class);
22             System.out.println(result);
23         } else {
24             System.out.println("Failed");
25         }
26         client.close();
27     }
28 }

In the above at line 15, we are creating an instance of “Invocation.Builder” class named “builder”.

At line 16, we are setting the language accepted by calling “acceptLanguage” method on the “builder” instance and passing the Locale object as an argument.

Remaining code is same as in previous posts.

In this way we can set the ACCEPT header using JAX-RS client api

Leave a Reply