To read a Response body from a Post Request , JAX-RS provide response.readEntity(String.class).

The next example is tested with Jersey 3.x

import jakarta.ws.rs.core.Response;

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

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();

  }

So the question here is how to read the response body from a post request ?

Solution

The best solution in this situation is to 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\":\"jt community\"}";

  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);

4. References

Tagged: