Spring REST 视图分辨率 - 不支持的内容类型



发布XML对象Foo /foo.xml时,我无法启动路径扩展视图分辨率,但收到错误

不支持的内容类型:文本/纯文本

这是没有发布任何Content-Type标题的结果。但favorPathExtention应该消除这种需求。知道为什么没有吗?


控制器

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

我想你误解了内容谈判的目的。

内容协商是关于如何生成响应,而不是如何解析请求。

你得到

不支持的内容类型:文本/纯文本

因为,对于 @RequestBody ,没有注册的 HttpMessageConverter 实例可以读取默认请求内容类型application/octet-stream(或者您的客户端可能使用 text/plain )。这一切都发生在处理为用 @RequestBody 注释的参数生成参数的RequestResponseBodyMethodProcessor中。

如果要在请求正文中发送 XML 或 JSON,请设置Content-Type


至于内容协商,使用您的配置和请求,DispatcherServlet将尝试生成内容类型为 application/xml 的响应。由于@ResponseBody,您将需要一个能够制作此类内容的HttpMessageConverter。你的MarshallingHttpMessageConverter应该足够了。如果不是,您可以编写自己的。

我通过将text/plain作为支持的媒体类型添加到消息转换器来解决问题,例如

@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    List<MediaType> jsonTypes = new ArrayList<>(jsonConverter.getSupportedMediaTypes());
    jsonTypes.add(MediaType.TEXT_PLAIN);
    jsonConverter.setSupportedMediaTypes(jsonTypes);
    converters.add(jsonConverter);
}

相关内容

最新更新