将 XML
对象 Foo
发布到 /foo.xml
时,我无法获取路径扩展 View 决议启动,但出现错误
Unsupported content type: text/plain
这是未发布任何 Content-Type
header 的结果。但 favorPathExtention
应该消除这种需求。知道为什么没有吗?
Controller
@RequestMapping(value="/foo.xml", method=ADD, produces="application/xml")
@ResponseStatus(HttpStatus.OK)
public @ResponseBody Foo add(@RequestBody Foo foo) {
return foo;
}
配置
@Configuration
@ComponentScan(basePackages="my.pkg.controller")
public class RestWebConfig extends WebMvcConfigurationSupport {
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MarshallingHttpMessageConverter(...));
converters.add(new MappingJackson2HttpMessageConverter());
}
@Override
protected void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true)
.ignoreAcceptHeader(true)
.useJaf(false)
.mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML);
}
}
最佳答案
我认为您误解了内容协商的目的。
内容协商是关于如何生成响应,而不是如何解析请求。
你得到
Unsupported content type: text/plain
因为,对于@RequestBody
,没有注册的HttpMessageConverter
实例可以读取application/octet-stream
的默认请求内容类型> (或者您的客户可能使用 text/plain
)。这一切都发生在 RequestResponseBodyMethodProcessor
中,它负责为用 @RequestBody
注释的参数生成参数。
如果您要在请求正文中发送 XML 或 JSON,请设置 Content-Type
。
对于内容协商,根据您的配置和请求,DispatcherServlet
将尝试生成内容类型为 application/xml
的响应。由于 @ResponseBody
,您将需要一个能够生成此类内容的 HttpMessageConverter
。您的 MarshallingHttpMessageConverter
应该足够了。如果不是,您可以自己编写。
关于java - Spring REST View 解析 - 不支持的内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19413023/