簡體   English   中英

找不到可接受的表示形式-406 Not Acceptable錯誤

[英]Could not find acceptable representation - 406 Not Acceptable error

我正在研究將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;
}

在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從來沒有問題)。 刪除此錯誤后,錯誤消失了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM