我有一个非常简单的Spring
应用程序(不是弹簧启动)。我已经实现了GET和POST控制器方法。 GET
方法工作正常。但POST
正在投掷415 Unsupported MediaType
。重现的步骤可在下面找到
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
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
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("/");
}
}
代码可在此处获取:
git clone https://bitbucket.org/SpringDevSeattle/springrestcontroller.git
./gradlew clean build tomatrunwar
这会旋转嵌入式tomcat。
现在你可以卷曲以下
curl -X GET -H "Content-Type: application/json" "http://localhost:8095/myApp/service/example/sample"
工作正常
但是
curl -X POST -H "Content-Type: application/json" '{
"id":1,
"name":"sai"
}' "http://localhost:8095/myApp/service/example/sample2"
投掷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>
答案 0 :(得分:4)
接受标题可能是个问题。
据我记忆,当你通过curl发送请求时,它会添加一个默认标题accept : */*
但是在JSON的情况下,您必须提及接受标题
为accept : application/json
,类似地,您已经提到了内容类型。
还有一点,我不知道那是什么,但你不认为你必须像那样放置“请求映射”
@RequestMapping(value="/sample" ...
@RequestMapping(value="/sample2" ...
这可能不是这种情况,但接受标题就是问题,我认为是主要问题。
解决方案2
既然你有这个代码
public String getResponse2(@RequestBody Person person)
我之前已经遇到过这个问题,解决方案二可能会有所帮助
FormHttpMessageConverter,当内容类型为application / x-www-form-urlencoded时,用于@RequestBody-annotated参数,不能像@ModelAttribute那样绑定目标类)。因此,您需要@ModelAttribute而不是@RequestBody
使用@ModelAttribute注释而不是像这样的@RequestBody
public String getResponse2(@ModelAttribute Person person)
我向某人提供了相同的答案并且有所帮助。 这是我的answer
答案 1 :(得分:4)
我找到了解决方案,我想发布在这里,以便其他人受益。
首先,我需要在我的类路径中包含jackson,我在build.gradle中添加如下:
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.5'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.5'
compile 'com.fasterxml.jackson.core:jackson-core:2.7.5'
接下来,我必须更改AppConfig
扩展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 MappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
}
这就是全部,一切都很顺利
答案 2 :(得分:0)
你可以尝试在curl
中使用-d选项吗?curl -H "Content-Type: application/json" -X POST -d
'{"id":"1,"name":"sai"}'
http://localhost:8095/myApp/service/example/sample2
此外,如果你使用Windows,你应该转义双引号
-d "{ \"id\": 1, \"name\":\"sai\" }"