415 Spring 应用程序中不支持 POST 请求的 MediaType

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38066591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:07:10  来源:igfitidea点击:

415 Unsupported MediaType for POST request in spring application

springspring-mvcspring-restcontroller

提问by brain storm

I have a very simple SpringApplication (NOT spring boot). I have implemented a GET and POST controller methods. the GETmethod works fine. But the POSTis throwing 415 Unsupported MediaType. Steps to reproduce are available below

我有一个非常简单的Spring应用程序(不是 spring boot)。我已经实现了 GET 和 POST 控制器方法。该GET方法工作正常。而是在POST415 Unsupported MediaType。重现步骤如下

ServiceController. java

ServiceController. java

package com.example.myApp.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


    @Controller
    @RequestMapping("/service/example")
    public class ServiceController {

        @RequestMapping(value="sample", method = RequestMethod.GET)
        @ResponseBody
    public String getResp() {
        return "DONE";
    }

    @RequestMapping(value="sample2", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public String getResponse2(@RequestBody Person person) {
        return "id is " + person.getId();
    }

}

class Person {

    private int id;
    private String name;

    public Person(){

    }

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

AppConfig.java

AppConfig.java

package com.example.myApp.app.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan("com.example.myApp")
public class AppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**").addResourceLocations("/test/").setCachePeriod(0);
        registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(0);
        registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(0);
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(0);
    }
}

AppInitializer.java

AppInitializer.java

package com.example.myApp.app.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {


        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext =
                new AnnotationConfigWebApplicationContext();

        rootContext.register(AppConfig.class);
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher =
                servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));

        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

    }


}

The code is available here:

该代码可在此处获得:

git clone https://bitbucket.org/SpringDevSeattle/springrestcontroller.git
./gradlew clean build tomatrunwar

This spins up embedded tomcat.

这会启动嵌入式 tomcat。

Now you can curl the following

现在您可以卷曲以下内容

curl -X GET -H "Content-Type: application/json" "http://localhost:8095/myApp/service/example/sample"

works fine

工作正常

But

curl -X POST -H "Content-Type: application/json" '{
    "id":1,
    "name":"sai"
}' "http://localhost:8095/myApp/service/example/sample2"

Throws 415 unsupported MediaType

抛出 415 个不受支持的 MediaType

<body>
        <h1>HTTP Status 415 - </h1>
        <HR size="1" noshade="noshade">
        <p>
            <b>type</b> Status report
        </p>
        <p>
            <b>message</b>
            <u></u>
        </p>
        <p>
            <b>description</b>
            <u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.</u>
        </p>
        <HR size="1" noshade="noshade">
        <h3>Apache Tomcat/7.0.54</h3>
    </body>

采纳答案by brain storm

I found the solution and I want to post here so it benefits others.

我找到了解决方案,我想在这里发帖,以便其他人受益。

Firstly I need to include Hymanson in my classpath, which I added in build.gradle as follows:

首先,我需要在我的类路径中包含 Hymanson,我在 build.gradle 中添加如下:

 compile 'com.fasterxml.Hymanson.core:Hymanson-databind:2.7.5'
    compile 'com.fasterxml.Hymanson.core:Hymanson-annotations:2.7.5'
    compile 'com.fasterxml.Hymanson.core:Hymanson-core:2.7.5'

Next, I have to change my AppConfigwhich extends WebMvcConfigurerAdapteras follows:

接下来,我必须更改 my AppConfigwhich 扩展WebMvcConfigurerAdapter如下:

@Configuration
@EnableWebMvc
@ComponentScan("com.example.myApp")
public class AppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**").addResourceLocations("/test/").setCachePeriod(0);
        registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(0);
        registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(0);
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(0);
    }


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        converters.add(new MappingHymanson2HttpMessageConverter());
        super.configureMessageConverters(converters);
    }
}

That is all and everything worked nicely

就是这样,一切都很好

回答by Tahir Hussain Mir

Accept Header might be the issue. As far as i remember, when you send a request via curl it adds a default header accept : */*
But in case of JSON you have to mention the accept header
as accept : application/json
similarly you have mentioned the content-Type.

接受标题可能是问题所在。据我所知,当您通过 curl 发送请求时,它会添加一个默认标头accept : */*
但在 JSON 的情况下,您必须提到接受标头,
就像accept : application/json
您提到的内容类型一样。

And little more, i dont know what is that, but don't you think you have to place "request mappings" like that

还有一点,我不知道那是什么,但你不认为你必须像那样放置“请求映射”

@RequestMapping(value="/sample" ...
@RequestMapping(value="/sample2" ...

This may not be the case, but accept header is the thing, i think is the main issue.
Solution 2
Since you have this code

情况可能并非如此,但接受标题是问题,我认为这是主要问题。
解决方案 2
因为你有这个代码

public String getResponse2(@RequestBody Person person)

I have already faced this problem before and the solution two may help here

我之前已经遇到过这个问题,解决方案二可能会在这里有所帮助

FormHttpMessageConverter which is used for @RequestBody-annotated parameters when content type is application/x-www-form-urlencoded cannot bind target classes as @ModelAttribute can). Therefore you need @ModelAttribute instead of @RequestBody

当内容类型为 application/x-www-form-urlencoded 时,用于 @RequestBody 注释参数的 FormHttpMessageConverter 不能像 @ModelAttribute 那样绑定目标类)。因此你需要 @ModelAttribute 而不是 @RequestBody

Either Use @ModelAttribute annotation instead of @RequestBody like this

要么像这样使用@ModelAttribute 注释而不是@RequestBody

public String getResponse2(@ModelAttribute Person person)

I provided the same answer to somebody and it helped. here is that answerof mine

我向某人提供了相同的答案,它有所帮助。这是我的答案

回答by Periklis Douvitsas

can you trying using the -d option in curl

您可以尝试在 curl 中使用 -d 选项吗

curl -H "Content-Type: application/json" -X POST -d
 '{"id":"1,"name":"sai"}'
 http://localhost:8095/myApp/service/example/sample2

Also, if you use windows you should escape double quotes

此外,如果您使用 Windows,您应该转义双引号

-d "{ \"id\": 1, \"name\":\"sai\" }"