注意
使用以下方式读取时可能会出现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