You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring应用POST请求返回400 Bad Request排查求助

解决Spring POST请求返回400 Bad Request的问题

针对你遇到的POST请求返回400错误,以下是具体的排查方向和解决方案:

1. 获取详细错误信息

400错误大多是请求体与实体类绑定失败导致,但默认返回信息不够明确。你可以添加全局异常处理器,捕获解析错误并返回具体原因:

package com.example.greenbottle.customer;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.converter.HttpMessageNotReadableException;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<String> handleJsonParseError(HttpMessageNotReadableException ex) {
        return ResponseEntity.badRequest().body("请求体解析失败:" + ex.getLocalizedMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleValidationError(MethodArgumentNotValidException ex) {
        String errorDetails = ex.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField() + ":" + error.getDefaultMessage())
                .collect(Collectors.joining(";"));
        return ResponseEntity.badRequest().body("参数验证失败:" + errorDetails);
    }
}

2. 确保实体类反序列化正常

你的Customer类同时存在有参和无参构造函数,Jackson反序列化时可能优先调用有参构造但未正确映射字段。给构造函数参数添加@JsonProperty注解,明确字段映射关系:

public Customer(@JsonProperty("name") String name,
                @JsonProperty("phoneNumber") String phoneNumber,
                @JsonProperty("createdAt") LocalDate createdAt) {
    this.name = name;
    this.phoneNumber = phoneNumber;
    this.createdAt = createdAt;
}

3. 验证日期格式配置

虽然你传入的2022-12-17是标准ISO日期格式,但部分Spring Boot版本可能需要显式配置Jackson对LocalDate的支持。在application.properties中添加以下配置:

spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.date-format=yyyy-MM-dd

4. 检查请求与实体类的字段匹配

确认请求体中的字段名与Customer类的字段完全一致(比如phoneNumber、createdAt的驼峰命名无拼写错误),同时确保请求头Content-Type: application/json正确无误,请求体的JSON语法无错误(比如英文引号、逗号)。

5. 调试实体类绑定结果

在Controller的POST方法中打印Customer对象,确认字段是否正确赋值:

@PostMapping
public void registerNewCustomer(@RequestBody Customer customer) {
    System.out.println("姓名:" + customer.getName());
    System.out.println("手机号:" + customer.getPhoneNumber());
    System.out.println("创建日期:" + customer.getCreatedAt());
    customerService.registerNewCustomer(customer);
}

内容的提问来源于stack exchange,提问作者Emi15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:55:27