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);
}
Http请求获取请求Body的数据
推荐阅读
- php-fpm开启报错-ERROR: An another FPM instance seems to already listen on /tmp/php-cgi.sock详解
- Windows下的Python 3.6.1的下载与安装(适合32bits和64bits)(图文详解)
- Windows下的Jupyter Notebook 的介绍(写给新手)(图文详解)
- 全网最全的Windows下Anaconda2 / Anaconda3里正确下载安装用来向微信好友发送消息的itchat库(图文详解)
- 全网最全的Windows下Python2 / Python3里正确下载安装用来向微信好友发送消息的itchat库(图文详解)
- Filebeat-1.3.1安装和设置(图文详解)(多节点的ELK集群安装在一个节点就好)(以Console Output为例)
- Filebeat之input和output(包含Elasticsearch Output 、Logstash Output、 Redis Output、 File Output和 Console Output)
- HUE配置文件hue.ini 的database模块详解(包含qlite、mysql、 psql、和oracle)(图文详解)(分HA集群和非HA集群)
- HUE配置文件hue.ini 的hbase模块详解(图文详解)(分HA集群和非HA集群)
- 【转】nginx的优缺点