如何接收Post请求Body里的参数
ApiPost测试数据
1 2 3 4 5 6 7 8 9 |
{ "list" : [ "{'time':'xxxxx','distinct_id':'xxxx','appId':'xxxx'}" , "{'time':'xxxxx','distinct_id':'xxxx','appId':'xxxx'}" , "{'time':'xxxxx','distinct_id':'xxxx','appId':'xxxx'}" , "{'time':'xxxxx','distinct_id':'xxxx','appId':'xxxx'}" ], "type" : 1 } |
Java接收数据
需要提前创建好对应的Bean
由于传递过来的数据是String类型,因此需要转换一步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import cn.hutool.json.JSONObject; @PostMapping ( "/data/callback" ) public Object testResponse( @RequestBody JSONObject jsonObject ) { JSONArray jsonList = jsonObject.getJSONArray( "list" ); ArrayList<DataEntity> list = new ArrayList<>(); for (Object jsObject : jsonList){ DataEntity dataEntity = JSONObject.parseObject(jsObject.toString(), DataEntity. class ); list.add(dataEntity); } Integer type = (Integer) jsonObject.get( "type" ); log.info(String.format( "本次共接收%d条数据,type=%d" ,list.size(),type)); for (DataEntity dataEntity : list) { log.info(dataEntity.toString()); } } |
SpringBoot获取参数常用方式
参数在body体中
在方法形参列表中添加@RequestBody注解
@RequestBody 作用是将请求体中的Json字符串自动接收并且封装为实体。如下:
1 2 3 4 5 |
@PostMapping ( "/queryCityEntityById" ) public Object queryCityEntityById( @RequestBody CityEntity cityEntity) { return ResultUtil.returnSuccess(cityService.queryCityById(cityEntity.getId())); } |
PathVaribale获取url路径的数据
如下:
1 2 3 4 5 6 7 |
@RestController public class HelloController { @RequestMapping (value= "/hello/{id}/{name}" ,method= RequestMethod.GET) public String sayHello( @PathVariable ( "id" ) Integer id, @PathVariable ( "name" ) String name){ return "id:" +id+ " name:" +name; } } |
RequestParam获取请求参数的值
获取url参数值,默认方式,需要方法参数名称和url参数保持一致
localhost:8080/hello?id=1000,如下:
1 2 3 4 5 6 7 8 |
@RestController public class HelloController { @RequestMapping (value= "/hello" ,method= RequestMethod.GET) public String sayHello( @RequestParam Integer id){ return "id:" +id; } }
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/qq_36811160/article/details/111362637
查看更多关于SpringBoot如何接收Post请求Body里面的参数的详细内容...