【springboot】springboot接收不同的Content-Type类型请求
1. Content-Type:application/json
application/json
:是以json字符串的格式请求
springboot中 application/json:只能以@requestBody注解接收对象
Postman请求示例:
后台示例:
@PostMapping(value = "/asset", produces = Constants.APPLICATION_JSON_UTF)
public AssertResultEntity Assets(@RequestBody AssertEntity assertEntity) {
// 获取邮箱前缀
String userName = assertEntity.getMailPrefix();
AssertItemEntity asset = assetService.getAssetByName(userName);
return AssertResultEntity.success(asset);
}
2. Content-Type:application/x-www-form-urlencoded
application/x-www-form-urlencoded
:浏览器默认请求,数据是jquery的Ajax请求的默认方式,这种方式的好处是浏览器都支持,在请求过程中会对数据进行序列化,以键值对的形式k1=v1&k2=v2
springboot 可以通过@requestParam()注解接收
后台示例:
@PostMapping(value = "/asset-change", produces = Constants.APPLICATION_WWW_FORM_URL_ENCODED)
public AssertResultEntity AssetsChange(@RequestParam(value = "asset_type") String assetType,
@RequestParam(value = "rid_list") List<Integer> ridList,
@RequestParam(value = "attr_name") String attrName,
@RequestParam(value = "origin_user") String originUser,
@RequestParam(value = "new_user") String newUser,
@RequestParam(value = "operator") String operator,
@RequestParam(value = "sign") String sign
) {
System.out.println(originUser);
return AssertResultEntity.success();
}
总结:
-
前端请求传Json对象则后端使用@RequestParam;
-
前端请求传Json对象的字符串则后端使用@RequestBody。
参考:
https://www.cnblogs.com/yikuan-919/p/10221758.html
https://www.xttblog.com/?p=3576
https://blog.csdn.net/feiyst/article/details/88431621