JAX-RS Jersey - How to Force a Response ContentType? Overwrite content negotiation

Jersey defines requests by looking at the accept header. I have a request that only accepts text / * - How can I get the response to be for example application / json?

@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON)
public MyResponseObject create() {
    return new MyResponseObject();
}

If the request is for a creation that only accepts text / Jersey, it will return 500. Is there a way around this? (I cannot change the header for accepting the request).

+3
source share
2 answers

Jersey also supports this through the ResourceConfig property PROPERTY_MEDIA_TYPE_MAPPINGS, which you can configure in your web.xml or programmatically through the Jersey API, as shown below:

 DefaultResourceConfig rc = new DefaultResourceConfig(MyResource.class);
 rc.getMediaTypeMappings().put("json", MediaType.APPLICATION_JSON_TYPE);
 rc.getMediaTypeMappings().put("xml", MediaType.APPLICATION_XML_TYPE);
 SimpleServerFactory.create("http://localhost:9090", rc);

, .json .xml URL.

+5

Source: https://habr.com/ru/post/1763992/


All Articles