Search code examples
javajerseyhttp-status

Is is possible to change HTTP status in MessageBodyWriter?


How can I change HTTP status in MessageBodyWriter in Jersey? I know I can change header and the body response message via httpHeaders and entityStream in writeTo method, but I dont know how to change the HTTP status.

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class MessageBodyWriterJSON implements MessageBodyWriter<Object> {

    @Override
    public void writeTo(Object t, Class<?> type, Type genericType,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders,
        OutputStream entityStream) throws IOException,
        WebApplicationException {
        // ...???
    }

}

Solution

  • You can change the http status by throwing a WebApplicationException.

    Response response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    throw new WebApplicationException(response);