In this post under JAXRS Client section, I will show with simple example how to use the JAXRS Client API to make a POST request to REST api resource.
Below is the complete code for the example
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.Entity;
6 import jakarta.ws.rs.client.Invocation;
7 import jakarta.ws.rs.client.WebTarget;
8 import jakarta.ws.rs.core.Response;
9
10 public class Example2 {
11 public static void main(String[] args) {
12 Client client = ClientBuilder.newClient();
13 WebTarget webTarget = client.target("https://jsonplaceholder.typicode.com/users");
14 Invocation.Builder builder = webTarget.request();
15 String data = "{\r\n" +
16 " \"title\": \"morpheus\",\r\n" +
17 " \"body\": \"leader\",\r\n" +
18 " \"userId\": 1\r\n" +
19 "}";
20 Entity<String> entity = Entity.json(data);
21 Invocation invocation = builder.buildPost(entity);
22 Response response = invocation.invoke();
23 if(response.getStatus() == 201) {
24 System.out.println("Successful");
25 String result = response.readEntity(String.class);
26 System.out.println(result);
27 } else {
28 System.out.println("Failed");
29 }
30 client.close();
31 }
32 }
In the above code, At line 12, we create an instance of “Client” interface taking the help of “ClientBuilder’s” static method “newClient”.
At line 13, we use the “Client” instance to create an instance of “WebTarget” interface by calling the “target” method on the “Client” instance.
At line 14, from the “WebTarget” instance we create an instance of “Invocation.Builder” class. We create an instance of “Invocation.Builder” class by calling “request” method on “WebTarget” instance.
At line 15, we create the Java String object that contains the data to be posted.
At line 20, we create an Entity instance. It encapsulates the Java object that we are planning to send through POST or PUT method.
At line 21, we get an instance of “Invocation” interface by calling “buildPost” method on the “Invocation.Builder” instance.
At line 22, we now actually send a POST request to the target url by calling “invoke” method on the “Invocation” instance.
This “invoke” method returns an instance of “Response” abstract class.
At line 23, we check the status of the response by calling “getStatus” method on the “Response” abstract class instance.
If successful, we read the data received from the response by calling “readEntity” method on “Response” abstract class instance. Refer to line 25.
Else we print “Failed” to the console.
At the end, at line 30, we close the “Client” instance. This is required and should not be skipped.
In this way, we can make REST API POST call using the JAXRS Client API.