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;
}
returnResponse.status(Response.Status.BAD_REQUEST.getStatusCode()) .build();
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
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();
}
}
© 2024 OneMinuteCode. All rights reserved.