无法使用 Spring 框架在请求映射中获取不同的内容类型

Unable to get different Content-Types in request mapping using Spring Framework

这是我的控制器class:

@Controller
@RequestMapping("/actuator")
public class HealthController {

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON)
    @ResponseBody
    public HealthModel getDump() throws JsonProcessingException {
        return new HealthModel();
        //return mapper.writeValueAsString(metrics.invoke());
    }

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN)
    @ResponseBody
    public String getHealth() {
        return "HEALTHY";
    }
}

型号:

public class HealthModel {

    @JsonProperty
    private String status;
    @JsonProperty
    private int id;

    public HealthModel(){
        this.status="WARN";
        this.id=2;
    }

}

请注意,我已将 /metrics 映射到 return jsonplain-text,具体取决于请求中的 Accept Header

当我在

提出请求时

curl -v -H "Accept: application/json" http://localhost:8080/myapp/actuator/metrics

我在 json 中得到了预期的响应 {"status":"WARN","id":2}.

然而,当我尝试

curl -v -H "Accept: text/plain" http://localhost:8080/myapp/actuator/metrics

我得到 HTTP/1.1 406 Not Acceptable


编辑

@EnableWebMvc
@Configuration
public class AppMvcConfig extends WebMvcConfigurerAdapter {

   @Resource(name = "appObjectMapper")
    private ObjectMapper appObjectMapper;

    @Resource(name = "modelObjectMapper")
    private ObjectMapper modelObjectMapper;

 @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
       
        final MappingJackson2HttpMessageConverter inputConverter = new MappingJackson2HttpMessageConverter();
        inputConverter.setObjectMapper(appObjectMapper);

        final MappingJackson2HttpMessageConverter outputConverter = new MappingJackson2HttpMessageConverter();
        outputConverter.setObjectMapper(modelObjectMapper);

        converters.add(new JacksonDualMapperConverter(appObjectMapper, modelObjectMapper));

        super.configureMessageConverters(converters);
    }

}

根据文档,@ResponseBody 表示 return 类型应该直接写入 HTTP 响应主体(而不是放在模型中,或解释为视图名称) .所以注释应该在那里。再看一遍,您的 produces 注释似乎不正确。 它应该是 produces = MediaType.TEXT_PLAIN_VALUE 而不是 produces = MediaType.TEXT_PLAIN。 我尝试了以下方法,它对我有用:

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
    @ResponseBody
    public String getHealth() {
        return "HEALTHY";
    }

您可能还需要添加 StringHttpMessageConverter

由于您要添加自定义 MessageConverter configureMessageConverters,这将关闭默认转换器注册 (see JavaDoc)。

因此当内容协商开始时,您只有一个消息转换器(Jackson 那个)只支持 JSON 媒体类型并且不知道如何处理 text/plain

您应该在列表中添加 StringHttpMessageConverter 以支持 text/plain

converters.add(new StringHttpMessageConverter());

以防万一有人仍然收到 Type mismatch: cannot convert from MediaType to String[] 错误:

解决方法是使用MediaType.APPLICATION_JSON_VALUE

而不是MediaType.APPLICATION_JSON

此致