[java] Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I am actually new to REST WS but really I don't get this 415 Unsupported Media Type.

I am testing my REST with Poster on Firefox and the GET works fine for me, also the POST (when it's a application/xml) but when I try application/json it doesn't not reach the WS at all, the server rejects it.

This is my URL: http:// localhost:8081/RestDemo/services/customers/add

This is JSON I'm sending: {"name": "test1", "address" :"test2"}

This is XML I'm sending:

<customer>
    <name>test1</name>
    <address>test2</address>
</customer>

and this is my Resource class:

@Produces("application/xml")
@Path("customers")
@Singleton
@XmlRootElement(name = "customers")
public class CustomerResource {

    private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>();

    public  CustomerResource() {
        // hardcode a single customer into the database for demonstration
        // purposes
        Customer customer = new Customer();
        customer.setName("Harold Abernathy");
        customer.setAddress("Sheffield, UK");
        addCustomer(customer);
    }

    @GET
    @XmlElement(name = "customer")
    public List<Customer> getCustomers() {
        List<Customer> customers = new ArrayList<Customer>();
        customers.addAll(customerMap.values());
        return customers;
    }

    @GET
    @Path("/{id}")
    @Produces("application/json")
    public String getCustomer(@PathParam("id") int cId) {
        Customer customer = customerMap.get(cId); 
        return  "{\"name\": \" " + customer.getName() + " \", \"address\": \"" + customer.getAddress() + "\"}";

    }

    @POST
    @Path("/add")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public String addCustomer(Customer customer) {
         //insert 
         int id = customerMap.size();
         customer.setId(id);
         customerMap.put(id, customer);
         //get inserted
         Customer result = customerMap.get(id);

         return  "{\"id\": \" " + result.getId() + " \", \"name\": \" " + result.getName() + " \", \"address\": \"" + result.getAddress() + "\"}";
    }

}

EDIT 1:

This is my Customer class:

@XmlRootElement 
public class Customer implements Serializable {

    private int id;
    private String name;
    private String address;

    public Customer() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

This question is related to java json web-services rest post

The answer is


In case you are trying to use ARC app from google and post a XML and you are getting this error, then try changing the body content type to application/xml. Example here


I had the same problem:

curl -v -H "Content-Type: application/json" -X PUT -d '{"name":"json","surname":"gson","married":true,"age":32,"salary":123,"hasCar":true,"childs":["serkan","volkan","aybars"]}' XXXXXX/ponyo/UserModel/json

* About to connect() to localhost port 8081 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* connected
* Connected to localhost (127.0.0.1) port 8081 (#0)
> PUT /ponyo/UserModel/json HTTP/1.1
> User-Agent: curl/7.28.1
> Host: localhost:8081
> Accept: */*
> Content-Type: application/json
> Content-Length: 121
> 
* upload completely sent off: 121 out of 121 bytes
< HTTP/1.1 415 Unsupported Media Type
< Content-Type: text/html; charset=iso-8859-1
< Date: Wed, 09 Apr 2014 13:55:43 GMT
< Content-Length: 0
< 
* Connection #0 to host localhost left intact
* Closing connection #0

I resolved it by adding the dependency to pom.xml as follows. Please try it.

    <dependency>
        <groupId>com.owlike</groupId>
        <artifactId>genson</artifactId>
        <version>0.98</version>
    </dependency>

Add Content-Type: application/json and Accept: application/json in REST Client header section


just change the content-type to application/json when you use JSON with POST/PUT, etc...


I get the same issue. In fact, the request didn't reach the jersey annoted method. I solved the problem with add the annotation: @Consumes(MediaType.APPLICATION_FORM_URLENCODED) The annotation @Consumes("/") don't work!

    @Path("/"+PropertiesHabilitation.KEY_EstNouvelleGH)
    @POST
    //@Consumes("*/*")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void  get__EstNouvelleGH( @Context HttpServletResponse response) {
        ...
    }

Don't return Strings in your methods but Customer objects it self and let JAXB take care of the de/serialization.


Just in case this is helpful to others, here's my anecdote:

I found this thread as a result of a problem I encountered while I was using Postman to send test data to my RESTEasy server, where- after a significant code change- I was getting nothing but 415 Unsupported Media Type errors.

Long story short, I tore everything out, eventually I tried to run the trivial file upload example I knew worked; it didn't. That's when I realized that the problem was with my Postman request. I normally don't send any special headers, but in a previous test I had added a "Content-Type": "application/json" header. OF COURSE, I was trying to upload "multipart/form-data." Removing it solved my issue.

Moral: Check your headers before you blow up your world. ;)


I had the same issue, as it was giving error-415-unsupported-media-type while hitting post call using json while i already had the

@Consumes(MediaType.APPLICATION_JSON) 

and request headers as in my restful web service using Jersey 2.0+

Accept:application/json
Content-Type:application/json

I resolved this issue by adding following dependencies to my project

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

this will add following jars to your library :

  1. jersey-media-json-jackson-2.25.jar
  2. jersey-entity-filtering-2.25.jar
  3. jackson-module-jaxb-annotations-2.8.4.jar
  4. jackson-jaxrs-json-provider-2.8.4.jar
  5. jackson-jaxrs-base-2.8.4.jar

I hope it will works for others too as it did for me.


I encountered the same issue in postman, i was selecting Accept in header section and providing the value as "application/json". So i unchecked and selected Content-Type and provided the value as "application/json". That worked!


If none of the solution worked and you are working with JAXB, then you need to annotate your class with @XmlRootElement to avoid 415 unsupported media type


I had similar problem while using in postman. for POST request under header section add these as

key:valuepair

Content-Type:application/json Accept:application/json

i hope it will work.


I had this issue and found that the problem was that I had not registered the JacksonFeature class:

// Create JAX-RS application.
final Application application = new ResourceConfig()
    ...
    .register(JacksonFeature.class);

Without doing this your application does not know how to convert the JSON to a java object.

https://jersey.java.net/documentation/latest/media.html#json.jackson


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time