Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST to Jersey REST service getting error 415 Unsupported Media Type

I am using a JAX-RS web application with Jersey and Tomcat. Get requests are fine however when I try to post JSON I get an HTTP status 415 - Unsupported Media Type.

Here is my simple HelloWorld.java:

package service;

import javax.ws.rs.*;

@Path("hello")
public class HelloWorld {
    @GET
    @Produces("text/plain")
    public String get() {
        return "hello world";
    }

    @POST
    @Consumes("application/json")
    public String post(JS input) {
        return input.hello;
    }

    public static class JS {
        public String hello;
    }
}

Here is the request I try in Postman (with 'application/json' header):

enter image description here Here is the project layout with libraries: enter image description here

I am using:

  • Java 7 x64
  • Jersey 2.17
  • Tomcat 7.0.62 x64

Thanks!

like image 230
Rob Crocombe Avatar asked May 24 '15 12:05

Rob Crocombe


People also ask

How do I fix 415 unsupported media type?

Fixing 415 Unsupported Media Type errorsEnsure that you are sending the proper Content-Type header value. Verify that your server is able to process the value defined in the Content-Type header. Check the Accept header to verify what the server is actually willing to process.

What does error code 415 mean?

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format. The format problem might be due to the request's indicated Content-Type or Content-Encoding , or as a result of inspecting the data directly.


1 Answers

The Jersey distribution doesn't come with JSON/POJO support out the box. You need to add the dependencies/jars.

Add all these

  • jersey-media-json-jackson-2.17
  • jackson-jaxrs-json-provider-2.3.2
  • jackson-core-2.3.2
  • jackson-databind-2.3.2
  • jackson-annotations-2.3.2
  • jackson-jaxrs-base-2.3.2
  • jackson-module-jaxb-annotations-2.3.2
  • jersey-entity-filtering-2.17

With Maven, below will pull all the above in

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

For any future readers not using Jersey 2.17 (and using jars directly instead of Maven), you can go here to find the Jersey version you are using, and see what transitive dependency versions you need. The current version of this Jersey dependency uses Jackson 2.3.2. That's the main thing you need to look out for.

like image 119
Paul Samsotha Avatar answered Sep 25 '22 02:09

Paul Samsotha