![](/img/trans.png)
[英]HTTP Status 415 – Unsupported Media Type error in Spring MVC with angular js
[英]Spring MVC - Ajax call returns an HTTP Status 415 – Unsupported Media Type
我想将表单数据提交给控制器,但是即使在HTTP请求中看到正在发送参数,我仍然收到415 HTTP错误。 这是我对控制器的JQuery / AJAX调用:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
dataType: "json",
type: 'POST',
url: "calculate",
data : JSON.stringify(data),
success : function(response){
alert("OK");
},
error : function(){
alert("Error");
}
});
这是我的控制器:
@RequestMapping(value = "calculate", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody void calculate (@RequestBody QueryElements queryElements, HttpServletRequest request) throws IOException {
System.out.println("OK");
}
现在发生的是,如果我在控制器中删除@RequestBody,则在调试中看到正在调用该控制器,但是显然我需要保留注释。
这是HTTP请求:
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:593
Content-Type:application/json; charset=UTF-8
Cookie:JSESSIONID=AD8FEA2E46709554189D687A7C65929D
Host:localhost:9082
Origin:http://localhost:9082
Referer:http://localhost:9082/cheexport/export?
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
X-Requested-With:XMLHttpRequest
{"bindListregInc":"","bindListregEsc":"","bindListprovInc":"","bindListprovEsc":"","bindListcomInc":"","bindListcomEsc":"","bindListcapInc":"","bindListcapEsc":"","bindListsitInc":"","bindListsitEsc":"","stringaInclusa":"","stringaEsclusa":"","consenso":"","clausola1c":"","sponsor":"","bindListcontrInc":"","bindListcontrEsc":"","bindListcliInc":"","bindListcliEsc":"","nomeContratto":"","customQuote":"","campiHeaderHidden":""}
当您期望使用JSON时,也许您有一个void计算方法。 尝试返回一些东西:
@RequestMapping(value = "calculate", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody ResponseEntity<?> calculate (@RequestBody QueryElements queryElements, HttpServletRequest request) throws IOException {
return ResponseEntity.ok("OK");
}
在您的@RequestMapping批注中,您应该添加consumps =“ application / json”,如下所示:@RequestMapping(value =“ someUrl”,消耗= {MediaType.APPLICATION_JSON_VALUE})
这将告诉Spring方法接受applicatin / json请求。
或者您可以尝试使用@RestController而不是@Controller
另外,尝试将“ contentType”添加到JS代码中。 $ .ajax({url:“ / api1 / tax”,数据:JSON.stringify(requestData),类型:方法,contentType:“ application / json; charset = utf-8”,成功:函数(数据){setTimeout( reloadTable,globalTimeout);},错误:函数(错误){console.log(error);}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.