Java使用PUT提交请求错误码400及415解决方案

时间:2025-02-18 08:32:10

文章目录

        • 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 : Unrecognized token 'id': was expecting ('true', 'false' or 'null')↵ at [Source: (PushbackInputStream); line: 1, column: 4]"
    path: "/taskCord"
    status: 400
    
  • 解决方案 data参数调用 ()函数
    <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访问示例