Core Java

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
        WebTarget target = client.target("http://localhost:8080/api/users");
 
        // 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.

Download
You can download the full source code of this example here: jax rs client read response body
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button