consumes适用于application/json,但不适用于text/plain

问题描述 投票:0回答:2

我是春天的新手,

我有一个控制器类如下:

我正在尝试设置 oilCount 值,因此我执行了 POST/PUT 请求。

当将内容类型设置为 application/json 时,它工作正常,但是当我设置为 text/plain 时,它不起作用。

@RequestMapping(value="testserver/config")
@Controller
public class TestServerConfigController {

    @RequestMapping(value="oilcount", method={RequestMethod.PUT,RequestMethod.POST})
    @ResponseBody
    public void setOilCount(@RequestBody Integer oilValue) throws Exception {
              //set the  oilvalue send as the response body

    }
}

假设添加消耗可以解决问题,我在代码中添加了以下内容

@RequestMapping(value="testserver/config", consumes = {"text/plain", "application/json"}** )
@Controller
public class TestServerConfigController {

    @RequestMapping(value="oilcount", method={RequestMethod.PUT,RequestMethod.POST})
    @ResponseBody
    public void setOilCount(@RequestBody Integer oilValue) throws Exception {
              //set the  oilvalue send as the response body

    }
}

但我仍然遇到同样的错误

org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型“文本/纯文本”

我错过了什么?

java spring spring-mvc
2个回答
1
投票

您缺少一个

HttpMessageConverter
,它可以解析响应正文中的
text/plain
并将其转换为
Integer

Spring已经提供了一个可以解析

HttpMessageConverter
application/json
。如果您的响应正文包含 JSON 内容,该内容是 JSON 数字(映射到 Java
Integer
),它可以为您进行转换。对于
text/plain
则不能说同样的话。

您需要实现自己的

HttpMessageConverter
来执行此解析和转换并注册它。通过Java配置,您可以使用类似
WebMvcConfigurationSupport#addDefaultHttpMessageConverters(List)
之类的东西来注册实例。 XML 配置必须有类似的东西。


0
投票

默认情况下,MappingJackson2HttpMessageConverter 支持 UTF-8 字符集的 application/json 和 application/*+json。可以通过设置supportedMediaTypes属性来覆盖它。我添加了转换器,它对我有用:

@Component
class MappingJackson2HttpMessageConverterWithTextPlainSupport(objectMapper: ObjectMapper) :
    MappingJackson2HttpMessageConverter(objectMapper) {
    init {
        supportedMediaTypes = supportedMediaTypes + MediaType.TEXT_PLAIN
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.