【问题标题】:Could not find acceptable representation - 406 Not Acceptable error找不到可接受的表示 - 406 Not Acceptable 错误
【发布时间】:2019-07-14 10:47:42
【问题描述】:

我正在处理将 Spring 版本从 4.3.2 升级到 5.1.1 的要求。升级后,我遇到 JSON 响应的 406 Not Acceptable

我调试了 AbstractMessageConverterMethodProcessor 类,发现 writeWithMessageConverters 方法在 4.x 和 5.x 版本的 spring 中的实现略有不同。

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;
}

在上述实现中,ContentType 始终以 text/html;charset=UTF-8 的形式出现,即使在将生产者设置为“application/json”之后也是如此。任何机构都可以帮助我理解为什么它不起作用以及如何解决这个问题。

@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;
}

【问题讨论】:

    标签: java spring-mvc


    【解决方案1】:

    在 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 来说从来不是问题)。删除此错误后,错误消失了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2014-11-12
      • 2015-03-13
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多