gpt4 book ai didi

spring - 使用 Spring Framework 无法在请求映射中获取不同的 Content-Type

转载 作者:行者123 更新时间:2023-12-04 08:00:54 25 4
gpt4 key购买 nike

这是我的 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返回 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);
}

}

最佳答案

以防万一有人仍然得到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com