天天看點

java 406_java - Spring JSON請求獲得406(不可接受)

java - Spring JSON請求獲得406(不可接受)

這是我的javascript:

function getWeather() {

$.getJSON('getTemperature/' + $('.data option:selected').val(), null, function(data) {

alert('Success');

});

}

這是我的控制器:

@RequestMapping(value="/getTemperature/{id}", headers="Accept=**; q=0.01

Accept-Language en-us,en;q=0.5

Accept-Encoding gzip, deflate

Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7

Connection keep-alive

X-Requested-With XMLHttpRequest

Referer http://localhost:8080/web/weather

Cookie JSESSIONID=7D27FAC18050ED84B58DAFB0A51CB7E4

有趣的說明:

我得到406錯誤,但hibernate查詢同時工作。這是tomcat日志所說的,每當我更改dropbox中的選擇時:

select weather0_.ID as ID0_0_, weather0_.CITY_ID as CITY2_0_0_, weather0_.DATE as DATE0_0_, weather0_.TEMP as TEMP0_0_ from WEATHER weather0_ where weather0_.ID=?

問題是什麼? 在之前有兩個類似的問題,我嘗試了所有接受的提示,但我認為它們不起作用......

有什麼建議? 随意問的問題...

21個解決方案

101 votes

406不可接受

由請求辨別的資源僅能夠根據請求中發送的接受報頭生成具有不可接受的内容特征的響應實體。

是以,您的請求接受标頭是application / json,您的控制器無法傳回該标頭。 當無法找到正确的HTTPMessageConverter來滿足@ResponseBody帶注釋的傳回值時,會發生這種情況。 在類路徑中給定某些3-d方庫時,使用headers="Accept=**"指令。

我成功地複制了你的場景,并且使用這兩個庫并且沒有headers="Accept=**時當然是假的。

這種行為有一個錯誤,但它被關閉為“無法重制”:被調用的方法沒有聲明它可以抛出,是以吞咽異常顯然是一個合适的解決方案(是的,這是諷刺)。 不幸的是,傑克遜沒有任何記錄......并且在代碼庫中有很多評論希望它能做到,是以我懷疑這不是唯一隐藏的問題。

kdgregory answered 2019-05-05T16:22:39Z

13 votes

我有同樣的問題,我的控制器方法執行但響應是錯誤406。我調試AbstractMessageConverterMethodProcessor#writeWithMessageConverters,發現方法ContentNegotiationManager#resolveMediaTypes總是傳回text/html,MappingJacksonHttpMessageConverter不支援。問題是org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy的工作時間早于org.springframework.web.accept.HeaderContentNegotiationStrategy,我的請求擴充/get-clients.html是我的錯誤406問題的原因。我剛剛更改了請求網址 至/get-clients。

atott answered 2019-05-05T16:23:07Z

9 votes

確定在類路徑中存在以下2 jar。

如果缺少任何一個或兩個,則會出現此錯誤。

jackson-core-asl-1.9.X.jar jackson-mapper-asl-1.9.X.jar

Raju Rathi answered 2019-05-05T16:23:42Z

5 votes

終于從這裡找到了答案:

将restful ajax請求映射到spring

我引用:

@RequestBody / @ ResponseBody注釋不使用普通的視圖解析器,它們使用自己的HttpMessageConverters。 為了使用這些注釋,您應該在AnnotationMethodHandlerAdapter中配置這些轉換器,如引用中所述(您可能需要MappingJacksonHttpMessageConverter)。

Jaanus answered 2019-05-05T16:24:28Z

3 votes

檢查dispatcherservlet.xml中的,如果沒有添加它。并添加

org.codehaus.jackson

jackson-core-asl

1.9.13

org.codehaus.jackson

jackson-mapper-asl

1.9.13

你的pom.xml中的這些依賴項

SHIVA answered 2019-05-05T16:25:03Z

2 votes

com.fasterxml.jackson.jaxrs

jackson-jaxrs-base

2.6.3

Rajan answered 2019-05-05T16:25:25Z

1 votes

在控制器中,響應體注釋不應該在傳回類型而不是方法上,如下所示:

@RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)

public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){

Weather weather = weatherService.getCurrentWeather(id);

return weather;

}

我還使用原始的jquery.ajax函數,并確定正确設定了contentType和dataType。

換句話說,我發現json的彈簧處理相當有問題。 當我使用字元串和GSON完成所有操作時更容易。

NimChimpsky answered 2019-05-05T16:26:09Z

1 votes

我遇到了同樣的問題,因為我錯過了@EnableMvc注釋。 (我的所有Spring配置都是基于注釋的,XML等價物将是mvc:annotation-driven)

jambriz answered 2019-05-05T16:26:39Z

1 votes

正如@atott所說。

如果你已經在你的pom.xml中添加了最新版本的Jackson,并且在你的動作方法上使用了233431328567328870,在你的動作方法中使用了233431328567328870,那麼你仍然得到了406(不可接受),我想你需要 在MVC DispatcherServlet上下文配置中嘗試此操作:

這就是我最終解決問題的方式。

Raven answered 2019-05-05T16:27:23Z

1 votes

Spring 4.3.10:我使用以下設定來解決問題。

第1步:添加以下依賴項

com.fasterxml.jackson.core

jackson-core

2.6.7

com.fasterxml.jackson.core

jackson-databind

2.6.7

org.codehaus.jackson

jackson-core-asl

1.9.13

org.codehaus.jackson

jackson-mapper-asl

1.9.13

第2步:在MVC DispatcherServlet上下文配置中添加以下内容:

class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">

從Spring 3.2開始,按照預設配置将favorPathExtension設定為true,因為如果請求uri有任何适當的擴充名,如.htm spring将優先擴充。 在第2步中,我添加了contentNegotiationManager bean來覆寫它。

Kevin Sebastian Fernandez answered 2019-05-05T16:28:14Z

1 votes

可能沒有人向下滾動這一點,但上述解決方案都沒有為我修複它,但制作了所有我的getter方法public。

我把我的getter知名度保留在package-private; 傑克遜決定找不到它們并且爆炸了。 (使用@JsonAutoDetect(getterVisibility=NON_PRIVATE)僅部分修複它。

Hazel Troost answered 2019-05-05T16:28:52Z

0 votes

確定你的類路徑中有正确的jackson版本

joyfun answered 2019-05-05T16:29:23Z

0 votes

檢查為@joyfun做了正确的傑克遜版本,但也檢查我們的标題...接受/可能不是由用戶端傳輸...使用firebug或等效的檢查您的擷取請求實際發送的内容。 我認為注釋的頭屬性/可能/正在檢查文字雖然我不是100%肯定。

Dave G answered 2019-05-05T16:29:56Z

0 votes

除了包含Spring servlet中所有可能的JAR,依賴項和注釋之外,我還有一個我無法解決的明顯問題。 最終我發現我有錯誤的檔案擴充名,我的意思是我有兩個單獨的servlet在同一個容器中運作,我需要映射到不同的檔案擴充名,其中一個是“.do”,另一個用于訂閱,随機命名為“。子”。 所有好,但SUB是通常用于電影字幕檔案的有效檔案擴充名,是以Tomcat覆寫了标題并傳回類似“text / x-dvd.sub ...”的内容是以一切都很好,但應用程式期待JSON但獲得字幕 是以我所要做的就是更改我添加的web.xml檔案中的映射:

sub

application/json

infinity answered 2019-05-05T16:30:29Z

0 votes

我有同樣的問題,遺憾的是,這裡沒有解決方案解決了我的問題,因為我的問題是在另一個班級。

我首先檢查了@bekur建議的所有依賴關系然後我檢查了從用戶端傳送到伺服器的請求/響應所有頭檔案都是由Jquery正确設定的。然後我檢查了RequestMappingHandlerAdapter MessageConverters并且所有7個都到位了,我真的開始讨厭春天了! 然後我更新到Spring 4.0.6.RELEASE到4.2.0.RELEASE我得到了另一個響應而不是上面的響應。 這是Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type

這是我的控制器方法

@RequestMapping(value = "/upload", method = RequestMethod.POST,produces = "application/json")

public ResponseEntity pictureUpload(FirewalledRequest initialRequest) {

DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) initialRequest.getRequest();

try {

Iterator iterator = request.getFileNames();

while (iterator.hasNext()) {

MultipartFile file = request.getFile(iterator.next());

session.save(toImage(file));

}

} catch (Exception e) {

return new ResponseEntity(new UploadPictureResult(),HttpStatus.INTERNAL_SERVER_ERROR);

}

return new ResponseEntity(new UploadPictureResult(), HttpStatus.OK);

}

public class UploadPictureResult extends WebResponse{

private List images;

public void setImages(List images) {

this.images = images;

}

}

public class WebResponse implements Serializable {

protected String message;

public WebResponse() {

}

public WebResponse(String message) {

this.message = message;

}

public void setMessage(String message) {

this.message = message;

}

}

解決方案是使UploadPictureResult不擴充WebResponse

出于某種原因,Spring在擴充WebResponse時無法确定如何轉換UploadPictureReslt

Adelin answered 2019-05-05T16:31:31Z

0 votes

com.fasterxml.jackson.core

jackson-databind

2.8.0

我不使用ssl身份驗證,這個jackson-databind包含jackson-core.jar和jackson-databind.jar,然後更改RequestMapping内容,如下所示:

@RequestMapping(value = "/id/{number}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)

public @ResponseBody Customer findCustomer(@PathVariable int number){

Customer result = customerService.findById(number);

return result;

}

注意:如果你的産品不是“application / json”類型,我沒有注意到這個并得到406錯誤,幫助這可以幫助你。

Crabime answered 2019-05-05T16:32:11Z

0 votes

檢查這個文章。spring mvc restcontroller傳回json字元串p / s:你應該将jack子映射配置添加到你的WebMvcConfig類

@Override

protected void configureMessageConverters(

List> converters) {

// put the jackson converter to the front of the list so that application/json content-type strings will be treated as JSON

converters.add(new MappingJackson2HttpMessageConverter());

// and probably needs a string converter too for text/plain content-type strings to be properly handled

converters.add(new StringHttpMessageConverter());

}

Anh Lam answered 2019-05-05T16:32:49Z

0 votes

這是springVersion = 5.0.3.RELEASE的更新答案。

以上答案将隻适用于年齡較大的springVersion< 4.1版本。 對于最新的spring,您必須在gradle檔案中添加以下依賴項:

compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: fasterxmljackson

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: fasterxmljackson

fasterxmljackson=2.9.4

我希望這對使用最新彈簧版本的人有所幫助。

-3 votes

你可以删除@RequestMapping中的headers元素并嘗試..

喜歡

我猜spring是一個'包含檢查',而不是接受标題的完全比對。 但仍然值得嘗試删除header元素并檢查。

stratwine answered 2019-05-05T16:34:19Z