In API response, I want to store any entity in the BODY and return a non-HTTP status of 200.

Asked 2 years ago, Updated 2 years ago, 88 views

running environment:
Windows, Java 1.8.0

I am currently writing the following code as an error response to an API using JAX-RS (Jersey).

Now, I want to return HTTP status such as BAD_REQUEST while storing any entity in the response in certain cases, but I don't know how.
(The code below does not seem to work because it simply setsStatus() to "ResponseObj" where HttpServletResponse is implemented.

@Path("API_01")//URL at API call

@POST
@Produce(MediaType.APPLICATION_JSON)
publicResponseObj execute(RequestObj request)throwsException {
    
    ResponseObj response=new ResponseObj();
    response.status="999";
    response.message="Error";
    
    response.setStatus(Status.BAD_REQUEST.getStatusCode());
    
    return response;
}
  • When you submit a POST request, Jersey automatically invokes the execute method above.
  • Jersey converts requests in JSON format to RequestObj
  • ResponseObj is a simple VO with scalar member variables, but in the above attempt
    ResponseObj uses HttpServletResponse as an implementation of HttpServletResponse. I tried to implement and set the HTTP status with setStatus().
    (As a result, 200 was successful.)
  • Separate,
    returnResponse.status(Response.Status.BAD_REQUEST.getStatusCode()) .build();
    When I tried , it returned with an HTTP status of 400 as expected, but the BODY portion of the response
    I didn't know how to store ResponseObj in .
    (We would like to store only ResponseObj contents in the body part of the HTTP response.)

I think I can set the HTTP status by getting the HTTPServletResponse for receiving the above request and settingStatus() on it, but I don't know how to get the HTTPServletResponse and set any HTTP status in the above context?

Or could you tell me how to store any entity in the BODY section of the Response generated using the Response Builder?

Also, if there is a problem with what you are trying to do and the implementation configuration itself, it would be very helpful if you could let me know.

java api

2022-09-30 14:33

1 Answers

You can achieve this by returning the Response type (javax.ws.rs.core.Response or jakarta.ws.rs.core.Response).


@Path("API_01")
public class MyResource {

    @POST
    @Produce(MediaType.APPLICATION_JSON)
    public Response execute (final RequestObj request) flows Exception {

        finalResponseObj response=newResponseObj();
        response.status="999";
        response.message="Error";

        return Response.status(Status.BAD_GATEWAY).entity(response).build();
    }
}


2022-09-30 14:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.