Spring REST视图分辨率-不支持的内容类型 [英] Spring REST view resolution - unsupported content type
问题描述
将XML
对象Foo
发布到/foo.xml
时,我无法获得路径扩展视图分辨率,但会收到错误
When posting an XML
object Foo
to /foo.xml
I can't get path extension view resolution to kick in, but get the error
不支持的内容类型:文本/纯文本
Unsupported content type: text/plain
这是未发布任何Content-Type
标头的结果.但是favorPathExtention
应该消除这种需求.知道为什么不这么做吗?
Which is a result of not posting any Content-Type
headers. But favorPathExtention
should remove that need. Any idea why it doesn't?
控制器
@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);
}
}
推荐答案
我认为您误解了内容协商的目的.
I think you've misunderstood the purpose of content negotiation.
内容协商用于响应的生成方式,而不是请求的解析方式.
Content negotiation is for how the response will be generated, not how the request will be parsed.
您得到
不支持的内容类型:文本/纯文本
Unsupported content type: text/plain
因为使用@RequestBody
,没有注册的HttpMessageConverter
实例可以读取默认的请求内容类型application/octet-stream
(或者您的客户端使用text/plain
).这一切都发生在RequestResponseBodyMethodProcessor
中,该处理为使用@RequestBody
注释的参数生成参数.
because, with @RequestBody
, there are no registeredHttpMessageConverter
instances that can read the default request content-type of application/octet-stream
(or maybe your client uses text/plain
). This all happens in the RequestResponseBodyMethodProcessor
which handles generating an argument for the parameter annotated with @RequestBody
.
如果要在请求正文中发送XML或JSON,请设置Content-Type
.
If you're going to send XML or JSON in your request body, set the Content-Type
.
对于内容协商,使用您的配置和请求,DispatcherServlet
将尝试生成内容类型为application/xml
的响应.由于@ResponseBody
,您将需要能够产生此类内容的HttpMessageConverter
.您的MarshallingHttpMessageConverter
应该足够了.如果不是这样,您可以编写自己的内容.
As for the content negotiation, with your config and request, the DispatcherServlet
will attempt to generate a response with content type application/xml
. Because of @ResponseBody
, you will need an HttpMessageConverter
capable of producing such content. Your MarshallingHttpMessageConverter
should be enough. If it isn't, you can write your own.
这篇关于Spring REST视图分辨率-不支持的内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!