这是我的 Controller 类:
@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
返回 json
或 plain-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);
}
}
最佳答案
以防万一有人仍然得到 Type mismatch: cannot convert from MediaType to String[]
错误:
解决方法是使用 MediaType.APPLICATION_JSON_VALUE
而不是 MediaType.APPLICATION_JSON
问候
关于spring - 使用 Spring Framework 无法在请求映射中获取不同的 Content-Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32403097/