我正在研究将Spring版本从4.3.2升级到5.1.1的要求。升级后,我遇到 406不可接受的JSON响应。
我调试了 AbstractMessageConverterMethodProcessor 类,发现在4.x和5.x版本的spring之间, writeWithMessageConverters 方法的实现略有不同。
MediaType selectedMediaType = null;
MediaType contentType = outputMessage.getHeaders().getContentType();
if (contentType != null && contentType.isConcrete()) {
if (logger.isDebugEnabled()) {
logger.debug("Found 'Content-Type:" + contentType + "' in response");
}
selectedMediaType = contentType;
}
在上述实现中,即使将生产者设置为“ application / json”,ContentType也始终以 text / html; charset = UTF-8 出现。任何机构都可以帮助我了解为什么它不起作用以及如何解决此问题。
@RequestMapping (value ="/BuyerListForAutocompleteQuery.af" produces = "application/json")
public @ResponseBody JSONObject getBuyerListForAutocompleteQuery(HttpServletRequest request, HttpServletResponse response) {
JSONObject jsonObject = new JSONObject();
//actual impl goes here
jsonObject.element("query", query);
jsonObject.element("suggestions", suggestions);
jsonObject.element("data", data);
return jsonObject;
}
答案 0 :(得分:0)
在Spring 4.x响应中,内容类型从请求标头中获取,而与Spring 5.x中一样,现在从响应标头中获取内容类型。仅仅是代码上的差异。
//Spring 5.x new code
MediaType selectedMediaType = null;
MediaType contentType = outputMessage.getHeaders().getContentType();
if (contentType != null && contentType.isConcrete()) {
if (logger.isDebugEnabled()) {
logger.debug("Found 'Content-Type:" + contentType + "' in response");
}
selectedMediaType = contentType;
}
在我的应用程序中,我们将响应类型显式设置为 text / html; charset = UTF-8 (对于spring 4.x来说从来没有问题)。删除此错误后,错误消失了。