Friday, January 16, 2015

Accept encoding with Jersey REST API

Consider following Jersey resource definition -
@Path("/data")
@GET
@Produces(MediaType.TEXT_HTML)
public String getData();
If the client does not provide HTTP request header "Accept" with value "text/html" you will see following exception in your application. To fix ensure client provided Accept encoding matches with what is defined by the REST API.
javax.ws.rs.WebApplicationException: null
        at com.sun.jersey.server.impl.uri.rules.TerminatingRule.accept(TerminatingRule.java:66) ~[jersey-server-1.17.jar:1.17]
        at com.sun.jersey.server.impl.uri.rules.ResourceObjectRule.accept(ResourceObjectRule.java:100) ~[jersey-server-1.17.jar:1.17]
        at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) ~[jersey-server-1.17.jar:1.17]
        at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84) ~[jersey-server-1.17.jar:1.17]
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511) [jersey-server-1.17.jar:1.17]
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442) [jersey-server-1.17.jar:1.17]
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391) [jersey-server-1.17.jar:1.17]
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381) [jersey-server-1.17.jar:1.17]
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416) [jersey-servlet-1.17.jar:1.17]
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538) [jersey-servlet-1.17.jar:1.17]
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716) [jersey-servlet-1.17.jar:1.17]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) [servlet-api-3.0.jar:na]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) [tomcat-catalina-7.0.42.jar:7.0.42]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [tomcat-catalina-7.0.42.jar:7.0.42]

2 comments:

  1. Hi there! This was really helpful, thanks! In my case I had to use 'application/json' since my method was annotated with @Consumes({MediaType.APPLICATION_JSON}).

    ReplyDelete