POST to Jersey REST service getting error 415 Unsupported Media Type
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.
Gone through a lot of the answers both on this page and others but to no avail. This actually worked for me:
METHOD 1:
Instead of passing JSONObject
as parameter to the resource method, pass a String
rather. Take the String
and create an JSONObject
with it
and then you can use it in you code. Like so,
@Path("/people")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response doGetperson(String jsonRequest) {
try {
JSONObject requestedJSON = new JSONObject(jsonRequest);
//So now you can use requestedJSON object created to do your stuff
return Response.ok("{\"name\":" + requestedJSON.getString("user") + "}").build();
} catch (Exception ex) {
return Response.ok("{ \"name\":\"\"}").build();
}
}
METHOD 2:
Adding this dependency as of September, 2017:
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-moxy -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.26</version>
</dependency>
Reference from here