Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC 415 Unsupported Media Type

I am using Spring 3.2 and try to use an ajax post request to submit an array of json objects. If this is relevant, I escaped all special characters.

I am getting an HTTP Status of 415.

My controller is:

@RequestMapping(value = "/save-profile", method = RequestMethod.POST,consumes="application/json")
    public @ResponseBody String saveProfileJson(@RequestBody String[] profileCheckedValues){
        System.out.println(profileCheckedValues.length);
        return "success";
    }

jquery is:

jQuery("#save").click(function () {
        var profileCheckedValues = [];
        jQuery.each(jQuery(".jsonCheck:checked"), function () {
            profileCheckedValues.push($(this).val());
        });
        if (profileCheckedValues.length != 0) {
            jQuery("body").addClass("loading");
            jQuery.ajax({
                type: "POST",
                contentType: "application/json",
                url: contextPath + "/sample/save-profile",
                data: "profileCheckedValues="+escape(profileCheckedValues),
                dataType: 'json',
                timeout: 600000,
                success: function (data) {
                    jQuery('body').removeClass("loading");
                },
                error: function (e) {
                    console.log("ERROR: ", e);
                    jQuery('body').removeClass("loading");
                }
            });
        }
    });

and an example of one of the objects from the array I am posting is the following json:

{
  "id": "534213341",
  "name": "Jack Lindamood",
  "first_name": "Jack",
  "last_name": "Lindamood",
  "link": "https://www.facebook.com/jack",
  "username": "jack",
  "gender": "male",
  "locale": "en_US",
  "updated_time": "2013-07-23T21:13:23+0000"
}

The error is:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method

Why is this error happening - does anyone know?

like image 738
jackyesind Avatar asked Aug 07 '13 11:08

jackyesind


People also ask

How do I fix 415 unsupported media type?

Fixing 415 Unsupported Media Type errors Ensure 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.

Why am I getting unsupported media type?

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.

How do you pass media type in Postman?

The Best Answer is You need to set the content-type in postman as JSON (application/json). Go to the body inside your POST request, there you will find the raw option. Right next to it, there will be a drop down, select JSON (application. json).


4 Answers

You may try with HttpServletRequest. it does not have any problem

  @RequestMapping(value = "/save-profile", method = RequestMethod.POST,consumes="application/json",headers = "content-type=application/x-www-form-urlencoded")
    public @ResponseBody String saveProfileJson(HttpServletRequest request){
       System.out.println(request.getParameter("profileCheckedValues"));
        return "success";
    }
like image 154
muthu Avatar answered Sep 30 '22 06:09

muthu


1) Add the following dependencies

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson-version}</version> // 2.4.3
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson-version}</version> // 2.4.3
</dependency>

2) If you are using @RequestBody annotation in controller method make sure you have added following in xml file

<mvc:annotation-driven />

This should resolve the 415 status code issue.

like image 32
Swapneel Avatar answered Sep 30 '22 06:09

Swapneel


You will need to add jackson and jackson-databind to the classpath. Spring will pick it up using it's MappingJacksonHttpMessageConverter

MappingJacksonHttpMessageConverter

An HttpMessageConverter implementation that can read and write JSON using Jackson's ObjectMapper. JSON mapping can be customized as needed through the use of Jackson's provided annotations. When further control is needed, a custom ObjectMapper can be injected through the ObjectMapper property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports (application/json).

like image 26
Bart Avatar answered Sep 30 '22 07:09

Bart


I had consume="application/json" in my request mapping configuration which expects a json input. When I sent a request which is not a JSON input Spring complained about the 415 Unsupported Media Type. So removing the consume="application/json" worked for me. So look into the request input and the accept media type in your Spring controller method signature. A mismatch would throw the 415 error. This will be most likely the reason for the issue.

like image 20
Lucky Avatar answered Sep 30 '22 05:09

Lucky