post请求发送Json数据
写接口用这个真的好用, 调试简直不要太爽!
传json到后台,用post方式,好处直接可以传一些复杂结构的数据, 通过spring的@RequestBody直接获取出对应的bean.
postman需要准备的:
1. 选post请求
2. Headers中添加 key: Content-Type value:application/json
3. Body中选raw, JSON(application/json)
4. 文本框中写入json参数, 简单的我不列了,列个有嵌套关系的json串
{
"name":"小明",
"age": 18,
"scores": [
{"score": 99, "type":1},
{"score": 77, "type":2}
]
}
1
2
3
4
5
6
7
8
这就相当于给后台传了一个字符串
java可以这样接参数
@PostMapping("/save")
public Student save(@RequestBody Student student)
1
2
3
如果不用@RequsetBody注解,那就要写方法从流中读取参数
public static String getRequestBody(HttpServletRequest req) throws IOException {
BufferedReader reader = req.getReader();
String input = null;
StringBuffer requestBody = new StringBuffer();
while((input = reader.readLine()) != null) {
requestBody.append(input);
}
return requestBody.toString();
}
当然返回的是字符串,如果需要转换成bean, 需要自己手动转换,用JsonObject之类。
注意:别用requset.getParamter 去接参数,接不到的,因为json串在requset的body中。
---------------------
作者:zyjcxc
来源:CSDN
原文:https://blog.csdn.net/zyjcxc/article/details/79511938
版权声明:本文为博主原创文章,转载请附上博文链接!