Luca
Luca

Reputation: 351

Jersey 2.22 and json unsupported media type

I'm creating a rest web service and i want to consume a json/xml object. I'm using jersey and when i try to post the request i obtain a 415 error unsopported media type. Here is the pom dependency

<dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.22</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>2.22</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.22</version>
    </dependency>

the web.xml

servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>
        org.glassfish.jersey.servlet.ServletContainer
    </servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>
            provider packages
        </param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>
            org.glassfish.jersey.media.multipart.MultiPartFeature; 
            org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature,
            org.glassfish.jersey.jackson.JacksonFeature
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jersey-serlvet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

and the webservice

@POST
@Path("FooPath")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public void insertFoo(FooClass fc){
    System.out.println(fc.getFoo());
}

anyone can help me?

Upvotes: 1

Views: 640

Answers (1)

wero
wero

Reputation: 32980

You try to send a application/json request using a form submit with the forms enctype set to application/json.

Unfortunately enctype only supports these values:

  • application/x-www-form-urlencoded (the default)
  • multipart/form-data
  • text/plain (in HTML5)

The browser silently ignores the enctype and you server rejects the request since it is most likely application/x-www-form-urlencoded.

In order to send the request as json you need to create an appropriate Ajax request from Javascript. Here is an example how to do that.

Upvotes: 1

Related Questions