SpringBoot如何接收Post請求Body里面的參數(shù)
如何接收Post請求Body里的參數(shù)
ApiPost測試數(shù)據(jù)
{ ? ? "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接收數(shù)據(jù)
需要提前創(chuàng)建好對應的Bean
由于傳遞過來的數(shù)據(jù)是String類型,因此需要轉換一步
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條數(shù)據(jù),type=%d",list.size(),type)); ? ? ? ? for (DataEntity dataEntity : list) { ? ? ? ? ? ? log.info(dataEntity.toString()); ? ? ? ? } ? ? } ? ?
SpringBoot獲取參數(shù)常用方式
參數(shù)在body體中
在方法形參列表中添加@RequestBody注解
@RequestBody 作用是將請求體中的Json字符串自動接收并且封裝為實體。如下:
@PostMapping("/queryCityEntityById") public Object queryCityEntityById(@RequestBody CityEntity cityEntity) { ? ? return ResultUtil.returnSuccess(cityService.queryCityById(cityEntity.getId())); }
PathVaribale獲取url路徑的數(shù)據(jù)
如下:
@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獲取請求參數(shù)的值
獲取url參數(shù)值,默認方式,需要方法參數(shù)名稱和url參數(shù)保持一致
localhost:8080/hello?id=1000,如下:
@RestController public class HelloController { ? ? @RequestMapping(value="/hello",method= RequestMethod.GET) ? ? public String sayHello(@RequestParam Integer id){ ? ? ? ? return "id:"+id; ? ? } } ?
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java8內存模型PermGen Metaspace實例解析
這篇文章主要介紹了Java8內存模型PermGen Metaspace實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03Java并發(fā)編程回環(huán)屏障CyclicBarrier
這篇文章主要介紹了Java并發(fā)編程回環(huán)屏障CyclicBarrier,文章繼續(xù)上文所介紹的Java并發(fā)編程同步器CountDownLatch展開主題相關內容,需要的小伙伴可以參考一下2022-04-04Springboot通用mapper和mybatis-generator代碼示例
這篇文章主要介紹了Springboot通用mapper和mybatis-generator代碼示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-12-12