从HttpServletRequest获取POST请求体
2022/7/23 23:25:18
本文主要是介绍从HttpServletRequest获取POST请求体,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
从HttpServletRequest获取POST请求体
注意
使用以下方式读取时可能会出现getInputStream() has already been called for this request报错信息( HttpServletRequest 流数据不可重复读)
出现原因:
- 不能和@Requestbody搭配使用
- 如果你的项目中有在过滤器中对post请求体作过处理,比如取出post的body进行MD5,以校验是否重复提交
第一种方式
StringBuffer data = new StringBuffer(); String line = null; BufferedReader reader = null; reader = request.getReader(); while (null != (line = reader.readLine())) { data.append(line); } jsonSt = data.toString();
第二种方式
String jsonSt = null; if ("POST".equalsIgnoreCase(request.getMethod())) { jsonSt = request.getReader().lines().collect(Collectors.joining(System.lineSeparator())); }
测试代码
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.util.Map; import java.util.stream.Collectors; /** * 从HttpServletRequest获取POST请求体 * * @author lyn * @date 2022/7/21 18:17 */ @RestController public class RequestController { @PostMapping("/request1") public String request1(HttpServletRequest request) throws IOException { StringBuffer data = new StringBuffer(); String line = null; BufferedReader reader = null; reader = request.getReader(); while (null != (line = reader.readLine())) { data.append(line); } return data.toString(); } @PostMapping("/request2") public String request2(HttpServletRequest request) throws IOException { if ("POST".equalsIgnoreCase(request.getMethod())) { return request.getReader().lines().collect(Collectors.joining(System.lineSeparator())); } return ""; } /** * 不能和@Requestbody搭配使用 * 原因: getInputStream() has already been called for this request,流不能读取第二次 * ,@Requestbody已经读取过一次了 * * @param paramMap * @param request * @return * @throws IOException */ @PostMapping("/request3") public String request3(@RequestBody Map<String, Object> paramMap, HttpServletRequest request) throws IOException { if ("POST".equalsIgnoreCase(request.getMethod())) { return request.getReader().lines().collect(Collectors.joining(System.lineSeparator())); } return ""; } }
结果示例
01
02
03
这篇关于从HttpServletRequest获取POST请求体的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南