POST JSON fails with 415 Unsupported media type, Spring 3 mvc

后端 未结 14 1541
执念已碎
执念已碎 2020-11-22 09: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.idProductCategor         


        
相关标签:
14条回答
  • 2020-11-22 10:31

    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){
    
    0 讨论(0)
  • 2020-11-22 10:34

    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.

    0 讨论(0)
  • 2020-11-22 10:35

    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.

    0 讨论(0)
  • 2020-11-22 10:36

    adding content type into the request as application/json resolved the issue

    0 讨论(0)
  • 2020-11-22 10:38

    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.

    0 讨论(0)
  • 2020-11-22 10:40

    I've had this happen before with Spring @ResponseBody and it was because there was no accept header sent with the request. Accept header can be a pain to set with jQuery, but this worked for me source

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

    The Content-Type header is used by @RequestBody to determine what format the data being sent from the client in the request is. The accept header is used by @ResponseBody to determine what format to sent the data back to the client in the response. That's why you need both headers.

    0 讨论(0)
提交回复
热议问题