Read Response Body in JAX-RS Client from a POST Request
JAX-RS (Jakarta API for RESTful Web Services) is a widely used framework for building RESTful web services in Java. It provides a client API that allows us to interact with RESTful services. When making a POST request using the JAX-RS client, we often need to read the response body returned by the server. This article will guide you through the process of reading the response body from a POST request using the JAX-RS client.
1. Setting Up Maven Dependencies
To use JAX-RS client features, add the following dependencies to your pom.xml
. We will use Jersey, the reference implementation of JAX-RS.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | < dependencies > <!-- Jersey Client --> < dependency > < groupId >org.glassfish.jersey.core</ groupId > < artifactId >jersey-client</ artifactId > < version >3.1.10</ version > </ dependency > <!-- Jersey Media JSON Binding --> < dependency > < groupId >org.glassfish.jersey.media</ groupId > < artifactId >jersey-media-json-binding</ artifactId > < version >3.1.10</ version > </ dependency > </ dependencies > |
2. Creating a Simple REST API (for Testing)
Before we create the client, let’s define a simple JAX-RS server to test our POST
request. Assume we are sending a POST
request to /api/users
with user details in JSON format.
01 02 03 04 05 06 07 08 09 10 11 | @Path ( "/users" ) public class UserResource { @POST @Consumes (MediaType.APPLICATION_JSON) @Produces (MediaType.APPLICATION_JSON) public Response createUser(User user) { user.setId( 1001 ); // Simulate ID assignment return Response.ok(user).build(); } } |
The User
class:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public class User { private int id; private String name; private String email; public User() { } public User(String name, String email) { this .name = name; this .email = email; } public int getId() { return id; } public void setId( int id) { this .id = id; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getEmail() { return email; } public void setEmail(String email) { this .email = email; } } |
This API accepts a POST
request with a User
object in JSON format, assigns it an ID, and returns the updated user as a response.
3. Implementing the JAX-RS Client
Now, let’s create a JAX-RS client to send a POST
request and read the response body.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class JaxrsClientExample { public static void main(String[] args) { // Create JAX-RS Client Client client = ClientBuilder.newClient(); // Define the target URL // Create the user request payload User user = new User( "John Fish" , "john.fish@jcg.com" ); // Send POST request Response response = target.request(MediaType.APPLICATION_JSON) .post(Entity.entity(user, MediaType.APPLICATION_JSON)); // Read response body as String String jsonResponse = response.readEntity(String. class ); System.out.println( "Response as String: " + jsonResponse); // Read response body as a User object User createdUser = response.readEntity(User. class ); System.out.println( "Response as User Object: " + createdUser.getId() + ", " + createdUser.getName()); client.close(); } } |
To begin, we need to create an instance of the JAX-RS client, which acts as the foundation for making HTTP requests. This is achieved using Client client = ClientBuilder.newClient();
, which initializes a new JAX-RS client instance. Once the client is ready, we define the target API endpoint using WebTarget target = client.target("http://localhost:8080/api/users");
. This establishes the base URL for our requests, allowing us to interact with the specified RESTful service.
When sending a POST
request, we use post(Entity.entity(user, MediaType.APPLICATION_JSON))
, which takes a User
object and converts it into a JSON payload. This ensures that the data is formatted correctly before being transmitted to the server.
After making the request, reading the response body is crucial for handling the server’s response. The simplest way to retrieve the response is as a raw JSON string using response.readEntity(String.class)
. This is useful when we want to process or log the raw response manually.
However, in many cases, we want to work directly with a Java object. Using response.readEntity(User.class)
, we can automatically convert the JSON response into a User
object, leveraging Jackson’s JSON binding capabilities. This simplifies data handling by allowing us to interact with the response as a strongly typed Java object instead of parsing JSON manually.
Finally, to ensure efficient resource management, we close the client using client.close();
, which releases any underlying resources and prevents potential memory leaks.
4. Handling Errors
It is essential to check the HTTP status before reading the response body.
1 2 3 4 5 6 | if (response.getStatus() == 200 ) { User createdUser = response.readEntity(User. class ); System.out.println( "User Created: " + createdUser.getName()); } else { System.out.println( "Error: " + response.getStatus() + " - " + response.readEntity(String. class )); } |
5. Running the Application
Start the JAX-RS server (full source code for the JAX-RS server is available from the download section), run the JAX-RS client, and you should see an output similar to the following.
1 2 | Response as String: { "email" : "john.fish@jcg.com" , "id" : 1001 , "name" : "John Fish" } Response as User Object: 1001 , John Fish |
6. Conclusion
This article demonstrated how to use the JAX-RS client API to send a POST
request and read the response body in different formats. We covered setting up dependencies, creating a simple REST API, implementing the client, and handling errors. This approach allows seamless integration with RESTful services while leveraging the power of JAX-RS.
7. Download the Source Code
This article explored how to read the response body using a JAX-RS client.
You can download the full source code of this example here: jax rs client read response body