springboot中@RequestBody和@RequestParam的区别

1. 问题场景

使用postman测试接口时,报错400

接口代码如下:

    @RequestMapping(value = "/realNameCheck", method = RequestMethod.POST)
    public String realNameCheck(@RequestParam(value = "timestamp") long timestamp,
                                @RequestParam("tradeId") String tradeId,
                                @RequestParam("photoName") String photoName,
                                @RequestParam("photoType") Integer photoType,
                                @RequestParam("photoSourceType") Integer photoSourceType,
                                @RequestParam("photoSource") String photoSource) throws IOException, ExecutionException, InterruptedException {

后台日志提示:

2. 解决办法

因为我使用的是@RequestParam,是用来接收content-type为application/x-www-form-urlencoded编码的数据(Content-type的默认值)。所以无法接收postman的body内容(格式为application/json),需修改为@RequestBody (就application/json类型的数据而言,使用注解@RequestBody可以将body里面所有的json数据传到后端,后端再进行解析。)

2.1 新增实体类

2.2 使用@RequestParam

(@RequestBody AIReq aireq) 

3. 引用

POST、GET、@RequestBody和@RequestParam区别
Spring中的HTTP请求与响应实体(以及 entity 与 body 的区别)

posted @ 2022-01-12 19:29  钱塘江畔  阅读(148)  评论(0)    收藏  举报