POST JSON fails with 415 Unsupported media type, S

2018-12-31 16:46发布

I am trying to send a POST request to a servlet. Request is sent via jQuery in this way:

var productCategory = new Object();
productCategory.idProductCategory = 1;
productCategory.description = "Descrizione2";
newCategory(productCategory);

where newCategory is

function newCategory(productCategory)
{
  $.postJSON("ajax/newproductcategory", productCategory, function(
      idProductCategory)
  {
    console.debug("Inserted: " + idProductCategory);
  });
}

and postJSON is

$.postJSON = function(url, data, callback) {
    return jQuery.ajax({
    'type': 'POST',
    'url': url,
    'contentType': 'application/json',
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
    });
};

With firebug I see that JSON is sent correctly:

{"idProductCategory":1,"description":"Descrizione2"}

But I get 415 Unsupported media type. Spring mvc controller has signature

    @RequestMapping(value = "/ajax/newproductcategory", method = RequestMethod.POST)
public @ResponseBody
Integer newProductCategory(HttpServletRequest request,
        @RequestBody ProductCategory productCategory)

Some days ago it worked, now it is not. I'll show more code if needed. Thanks

12条回答
只若初见
2楼-- · 2018-12-31 16:58

1.a. Add following in applicationContext-mvc.xml

xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc

  1. add jackson library
查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 16:59

I managed out how to make it works. Tell me in case I am wrong. I used only one way to serialize/deserialize: I removed all annotations regarding this (@JSONSerialize and @JSONDeserialize) and registered Serializers and Deserializers in CustomObjectMapper class. I didn't find an article explaining this behaviour but I resolved in this way. Hope it's useful.

查看更多
初与友歌
4楼-- · 2018-12-31 17:00

I had a similar problem but found the issue was that I had neglected to provide a default constructor for the DTO that was annotated with @RequestBody.

查看更多
浅入江南
5楼-- · 2018-12-31 17:00

A small side note - stumbled upon this same error while developing a web application. The mistake we found, by toying with the service with Firefox Poster, was that both fields and values in the Json should be surrounded by double quotes. For instance..

[ {"idProductCategory" : "1" , "description":"Descrizione1"}, 
  {"idProductCategory" : "2" , "description":"Descrizione2"} ]

In our case we filled the json via javascript, which can be a little confusing when it comes with dealing with single/double quotes, from what I've heard.

What's been said before in this and other posts, like including the 'Accept' and 'Content-Type' headers, applies too.

Hope t'helps.

查看更多
路过你的时光
6楼-- · 2018-12-31 17:04

Spring boot + spring mvn

with issue @PostMapping("/addDonation") public String addDonation(@RequestBody DonatorDTO donatorDTO) {

with solution @RequestMapping(value = "/addDonation", method = RequestMethod.POST) @ResponseBody public GenericResponse addDonation(final DonatorDTO donatorDTO, final HttpServletRequest request){

查看更多
无色无味的生活
7楼-- · 2018-12-31 17:10

I had the same problem. I had to follow these steps to resolve the issue:

1. Make sure you have 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. Create the following filter:

    public class CORSFilter extends OncePerRequestFilter {

        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {

            String origin = request.getHeader("origin");
            origin = (origin == null || origin.equals("")) ? "null" : origin;
            response.addHeader("Access-Control-Allow-Origin", origin);
            response.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, DELETE, OPTIONS");
            response.addHeader("Access-Control-Allow-Credentials", "true");
            response.addHeader("Access-Control-Allow-Headers",
                    "Authorization, origin, content-type, accept, x-requested-with");

            filterChain.doFilter(request, response);
        }
    }

3. Apply the above filter for the requests in web.xml

    <filter>
        <filter-name>corsFilter</filter-name>
        <filter-class>com.your.package.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>corsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

I hope this is useful to somebody.

查看更多
登录 后发表回答