JAX-RS – How to read response body from a post request?

In JAX-RS, we can use response.readEntity(String.class) to read the response body from a post request.


import jakarta.ws.rs.core.Response;

  Response response = //...
  // read response body
  String body = response.readEntity(String.class);

P.S Tested with Jersey 3.x

1. Problem

Below is a JAX-RS POST request endpoint to accept a JSON input and return a JSON response.


  // POST, accepts json and return JSON response
  @Path("/create")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response search(User user) {

      JSONObject json = // search by API
      return Response.status(Response.Status.OK)
                .entity(json.toString()).build();

  }

How to read the response body from a post request?


  Client c = ClientBuilder.newClient();
  WebTarget target = c.target("http://localhost:8080");

  String search = "{\"id\":1,\"name\":\"mkyong\"}";

  Response response = target.path("json/search")
          .request(MediaType.APPLICATION_JSON)
          .post(Entity.entity(json, MediaType.valueOf("application/json")));

  // return an object? how to read the response body?
  Object entity = response.getEntity();

2. Solution

We can use response.readEntity(String.class) to read the response body from a post request.


  Client c = ClientBuilder.newClient();
  WebTarget target = c.target("http://localhost:8080");

  String search = "{\"id\":1,\"name\":\"mkyong\"}";

  Response response = target.path("json/search")
          .request(MediaType.APPLICATION_JSON)
          .post(Entity.entity(json, MediaType.valueOf("application/json")));

  // return an object? how to read the response body?
  // Object entity = response.getEntity();

  // read response body
  String actual = response.readEntity(String.class);

  String expected = "{\"status\":\"ok\"}";
  JSONAssert.assertEquals(expected, actual, false);

3. Download Source Code

$ git clone https://github.com/mkyong/jax-rs

$ cd jax-rs/jersey/jersey-json-moxy/

$ Refer to the endpoints and unit tests

4. References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments