Http请求获取请求Body的数据


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);
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM