本文主要是介绍Java使用PUT提交请求错误码400及415解决方案,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 0. 初始状态
- 1. 请求报错 `400` Required int parameter 'id' is not present
- 2. `415` 不支持 'application/x-www-form-urlencoded;charset=UTF-8
- 3. `400` Unrecognized token 'id': was expecting ('true', 'false' or 'null')
- 4. delete操作
0. 初始状态
- 前端
<script>$("#btn").on("click", function (e) {$.ajax({url: "/xxx",type: "put",data: {'id': 1,'name': '你猜'}})});
</script>
- 后端
@PutMapping("/test")public String updateTaskCordName(@RequestParam(name="id") int id, @RequestParam(name="name") String name) {//业务代码
}
1. 请求报错 400
Required int parameter ‘id’ is not present
- 问题描述
error: "Bad Request"
message: "Required int parameter 'id' is not present"
path: "/test"
status: 400
- 解决方案 更改后端代码
@PutMapping("/test")public String updateTaskCordName(@RequestBody Map<String, String> map) {Integer id = Integer.parseInt(map.get("id"));String name = map.get("name");//业务代码
}
2. 415
不支持 'application/x-www-form-urlencoded;charset=UTF-8
- 问题描述
error: "Unsupported Media Type" message: "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported" path: "/test" status: 415
- 解决方案
ajax 请求添加配置参数contentType: "application/json; charset=utf-8",
即,前端<script>$("#btn").on("click", function (e) {$.ajax({url: "/xxx",type: "put",contentType: "application/json; charset=utf-8",data: {'id': 1,'name': '你猜'}})}); </script>
3. 400
Unrecognized token ‘id’: was expecting (‘true’, ‘false’ or ‘null’)
- 问题描述
error: "Bad Request" message: "JSON parse error: Unrecognized token 'id': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'id': was expecting ('true', 'false' or 'null')↵ at [Source: (PushbackInputStream); line: 1, column: 4]" path: "/taskCord" status: 400
- 解决方案 data参数调用 JSON.stringify()函数
<script>$("#btn").on("click", function (e) {$.ajax({url: "/xxx",type: "put",contentType: "application/json; charset=utf-8",data: JSON.stringify({'id': 1,'name': '你猜'})})}); </script>
附:
4. delete操作
@DeleteMapping("/db/{id}")
public String deleteById(@PathVariable(name="id") int id) {//业务代码
}
<script>$("#btn").on("click", function (e) {$.ajax({url: "/db"+1,type: "delete" })});
</script>
Spring Boot Rest访问示例
这篇关于Java使用PUT提交请求错误码400及415解决方案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!