java - Spring REST View 解析 - 不支持的内容类型

标签 java xml json spring rest

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/

相关文章:

java - 在java中打印一个平方根符号(√)

java - 使用 Java 获取 Neo4j 嵌入式图形数据库的 Subgraph

java - 如何使用java更改XML节点的值?

c# - WCF wsHttpBinding 和 XML 签名

javascript - HTML/Javascript/Jquery ListView ?

java - 重新创建特定的 JSON 结构

java - CTRL-C如何与Java程序一起工作

java - Spring Integration FileHeader.OriginalFile 被忽略

javascript - Ajax 调用成功,但错误 block 正在执行

android - 如何在android中的表中添加数据