Spring MVC 415 Unsupported Media Type

61,903

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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.

Share:
61,903
jackyesind
Author by

jackyesind

Updated on May 18, 2020

Comments

  • jackyesind
    jackyesind almost 4 years

    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?

  • jackyesind
    jackyesind over 10 years
    Is there any possible to send array of json to spring controller
  • jackyesind
    jackyesind over 10 years
    when i checked in firebug the param has valid json. In java side how would i get
  • jackyesind
    jackyesind over 10 years
    I already included jackson-core-2.0.6.jar. public @ResponseBody String saveProfileJson(@RequestBody String[] profileCheckedValues) instead of string what would i give i don't have objects for that json
  • Bart
    Bart over 10 years
    You probably need to add the jackson-databind package as well
  • Arjan
    Arjan over 10 years
    @RequestParam might work as well. And also in the jQuery call, remove setting the contentType: sending an array with name profileCheckedValues (which happens to hold JSON strings, but could have been anything) is not application/json but simply the default application/x-www-form-urlencoded.
  • Arjan
    Arjan over 10 years
    And for arrays, use getParameterValues.
  • Arjan
    Arjan over 10 years
    Again, @jackyesind, what does "it does not works" mean? (What do you see? You need to be specific; you need to be much more detailed.) Also, did you try getParameterValues? And @RequestParam? Please read Help Vampires: A Spotter’s Guide. I'm no longer responding to your requests, but: success.
  • Arjan
    Arjan over 10 years
    datatype is what the server sends back. Also, it's not formatted as a MIME type, but defined by jQuery.
  • muthu
    muthu over 10 years
    @Arjan. Sorry. If i use getParameterValues means it returns null only
  • Arjan
    Arjan over 10 years
    How did you test, muthu? getParameterValues should return the same as getParameter, if there's just one value. But indeed it depends on how jQuery creates the request. That jQuery Ajax request in @jackyesind's question has bugs too.
  • Aditzu
    Aditzu almost 7 years
    I had 415 problem because of using codehaus dependency instead of fasterxml. Thanks! Worked like a charm
  • Kurt Miller
    Kurt Miller about 6 years
    Awesome...But why did you use HttpServletRequest ? I tried @ResponseBody final MyObject obj with the same settings for consumes and headers but it failed....