首页 > 技术文章 > Http请求获取请求Body的数据

Lay-zsp 2020-12-01 15:43 原文

1、流方法读取
@RequestMapping(value = "/http/test", method = RequestMethod.POST)
public void getHttpBody(HttpServletRequest request) throws Exception {
String str = "";
// 通过http请求的req中获取字节输入流
InputStream is = request.getInputStream();
// 用此类的原因是缓冲区在数据写入到字节数组中时会自动增长
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 定义一个字节数组
byte[] bytes = new byte[1024];
// 遍历输入流
for (int length; (length=is.read(bytes)) != -1;) {
// 写入到输出流中
bos.write(bytes,0,length);
}
// 输出流再转换为字节数组
byte[] resBytes = bos.toByteArray();
// 字节转换为字符串
str = new String(resBytes,"UTF-8");
// 关闭流
bos.close();
is.close();
System.out.println(str);
JSONObject json = JSON.parseObject(str);
String body = json.getString("Body");
System.out.println(body);
}
2、字符串方法获取
@RequestMapping(value = "/string/test", method = RequestMethod.POST)
public void getHttpBodyByStr(HttpServletRequest request) throws Exception {
// 定义一个字符输入流
BufferedReader br = null;
// 定义一个可变字符串 这里不考虑线程安全问题 所以用StringBuilder
StringBuilder sb = new StringBuilder("");
br = request.getReader();
String str;
while ((str = br.readLine()) != null){
sb.append(str);
}
br.close();
String resStr = sb.toString();
System.out.println(resStr);
JSONObject json = JSON.parseObject(resStr);
String body = json.getString("Body");
System.out.println(body);
}

推荐阅读