Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML
Asked Answered
A

15

91

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;
    }

}
Aristotelianism answered 2/8, 2012 at 8:39 Comment(2)
How does your Customer class look like? What JAXB annotations do you use on it?Artois
Thanks, I updated to the code with my Customer class.Aristotelianism
I
21

The issue is in the deserialization of the bean Customer. Your programs knows how to do it in XML, with JAXB as Daniel is writing, but most likely doesn't know how to do it in JSON.

Here you have an example with Resteasy/Jackson http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/

The same with Jersey: http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

Interosculate answered 2/8, 2012 at 8:55 Comment(15)
In these examples the input is exactly the same as mine, the return is different (like Daniel said) but my problem is ahead and I am not hitting the class at all.Aristotelianism
@Maged do you use resteasy or jersey?Interosculate
@Maged Did you update your web.xml like explained in the article?Interosculate
Yeap I did add the mapping bit <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param>Aristotelianism
@Maged can you try to remove the default constructor on your customer bean?Interosculate
unfortunately it gives back same error and doesn't access the service...this is really weird because I found a lot of posts and everything seem to be fine and similar to what I have.Aristotelianism
let us continue this discussion in chatInterosculate
problem was that library jersey-jason was missing! Thank you.Aristotelianism
where is the pom.xml file is located, i have found around 8 when i search in the folder please helpCosmos
@Naveen did you download the project example?Interosculate
No. i have downloaded mulesoft.com/ty/dl/studio-linux and i have tried one example blog.raml.org/mocking-service-walkthrough. but it is have the same error message. message = "Unsupported media type"; when i acces from ios device it is getting when browser it is working fine.Cosmos
@Naveen pom.xml is specific to java code. iOs does not use java. This question is about java.Interosculate
Solved the issue from this link #19397196 from the ios part we have to mention Make the Content-Type "application/json;odata=verbose" in your POST requestCosmos
@Magini Have you solved this problem? I came across the same one.Holloweyed
very helpful description of the problem is available at ev9d9.blogspot.de/2013/05/doing-json-on-cxf.htmlLail
M
149

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

Maraud answered 21/11, 2012 at 8:40 Comment(10)
Where is the REST Client header section?Eolanda
if you are using curl call from command line then you can add the header as follows: [$> curl -H "Content-Type: application/json" -X POST -d '{"name":"my_name","password":"123456"}' localhost:8080/url]Shabuoth
Need your help, i am new in this rest api creation, where is the EST Client header section is located?Cosmos
For anyone who reached here from another language and that language was Ruby and you're using rest-client, this answer helped me a ton. Example usage response = RestClient.post "https://pod12.salesforce.com/services/data/v33.0/sobjects/Contact/", {Email: user.email, LastName: user.last_name, FirstName: user.first_name, Phone: user.phone}.to_json, {Authorization: "Bearer #{access_token}", :"Content-Type" => "application/json", :"Accept" => "application/json"}Cretin
Helped me on Python as well. Remember to pass the payload as JSON: requests.post("/login", data = json.dumps(loginCredentials), headers = {"Content-Type": "application/json", "Accept": "application/json"})Wondering
precise answer. It saved my time.Recalcitrate
it would be helpful if you could post a code example of how this is done within the context of the question.Prototrophic
If "Content-Type":"application/json" doesn't help, try "Content-Type":"text/xml"Motherofpearl
My problem had nothing to do with JAXRS - I was trying to hand-make a request and the client header was not there. This answered it for me.Rode
@BadhonJain you will probably get a 406 responseDancer
I
21

The issue is in the deserialization of the bean Customer. Your programs knows how to do it in XML, with JAXB as Daniel is writing, but most likely doesn't know how to do it in JSON.

Here you have an example with Resteasy/Jackson http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/

The same with Jersey: http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

Interosculate answered 2/8, 2012 at 8:55 Comment(15)
In these examples the input is exactly the same as mine, the return is different (like Daniel said) but my problem is ahead and I am not hitting the class at all.Aristotelianism
@Maged do you use resteasy or jersey?Interosculate
@Maged Did you update your web.xml like explained in the article?Interosculate
Yeap I did add the mapping bit <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param>Aristotelianism
@Maged can you try to remove the default constructor on your customer bean?Interosculate
unfortunately it gives back same error and doesn't access the service...this is really weird because I found a lot of posts and everything seem to be fine and similar to what I have.Aristotelianism
let us continue this discussion in chatInterosculate
problem was that library jersey-jason was missing! Thank you.Aristotelianism
where is the pom.xml file is located, i have found around 8 when i search in the folder please helpCosmos
@Naveen did you download the project example?Interosculate
No. i have downloaded mulesoft.com/ty/dl/studio-linux and i have tried one example blog.raml.org/mocking-service-walkthrough. but it is have the same error message. message = "Unsupported media type"; when i acces from ios device it is getting when browser it is working fine.Cosmos
@Naveen pom.xml is specific to java code. iOs does not use java. This question is about java.Interosculate
Solved the issue from this link #19397196 from the ios part we have to mention Make the Content-Type "application/json;odata=verbose" in your POST requestCosmos
@Magini Have you solved this problem? I came across the same one.Holloweyed
very helpful description of the problem is available at ev9d9.blogspot.de/2013/05/doing-json-on-cxf.htmlLail
M
19

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. ;)

Megmega answered 14/3, 2014 at 19:47 Comment(1)
+1 for the advice of "make sure the toaster is plugged in". Just had this same issue and it is easy to overlook when you are convinced the problem is in the code.Prostyle
N
9

In my case, the following dependency was missing:

<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-resteasy-reactive-jackson</artifactId>
</dependency>
Narrows answered 27/9, 2022 at 2:26 Comment(0)
C
3

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

Cabrales answered 30/4, 2014 at 18:51 Comment(2)
can you explain a little more? I almost tried everything and I think I'm missing this point. where should I do this registration? ThanksImplode
Thanks a lot, I encountered this while starting a grizzly server. When started by IDE or mvn:exec everything properly, but not when using a jar with dependencies. You made my day sir !Earhart
S
1

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>
Steroid answered 9/4, 2014 at 14:3 Comment(0)
C
1

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) {
        ...
    }
Checkmate answered 7/8, 2017 at 11:30 Comment(0)
C
0

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

Cowherb answered 2/8, 2012 at 8:49 Comment(1)
Could be but I think here the problem is ahead, I am not hitting the service at all.Aristotelianism
A
0

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.

Assurgent answered 21/7, 2018 at 16:21 Comment(0)
C
0

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

Colliery answered 10/1, 2019 at 5:56 Comment(0)
C
0

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

Coreligionist answered 14/5, 2019 at 10:41 Comment(0)
C
0

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!

Creditor answered 7/11, 2019 at 16:9 Comment(0)
C
0

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

Circinate answered 7/9, 2020 at 9:57 Comment(0)
S
0

you need to be consistent with choosing reactive or normal one that was my issue but after i changed it to reactive it works fine.

implementation("io.quarkus:quarkus-resteasy-reactive-jackson")
implementation("io.quarkus:quarkus-resteasy-reactive")
Situated answered 1/11, 2023 at 13:10 Comment(0)
M
-1

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.

Montpellier answered 14/6, 2020 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.