本文共 2080 字,大约阅读时间需要 6 分钟。
使用getReader()来读取请求的主体
String payloadRequest = getBody(request);
public static String getBody(HttpServletRequest request) throws IOException { String body = null; StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } } else { stringBuilder.append(""); } } catch (IOException ex) { throw ex; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { throw ex; } } } body = stringBuilder.toString(); return body; }
您可以使用缓冲区读取器从请求读取
// Read from request StringBuilder buffer = new StringBuilder(); BufferedReader reader = request.getReader(); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } String data = buffer.toString()
Java 8stream
String body = request.getReader().lines() .reduce("", (accumulator, actual) -> accumulator + actual);
使用Apache Commons IO,您可以在一行中执行此操作。
IOUtils.toString(request.getReader())
如果在Java 8中正文的内容是一个string,你可以这样做:
String body = request.getReader().lines().collect(Collectors.joining());
你只需要
request.getParameterMap()
获取POST和GET参数。
该方法返回一个Map 。
您可以阅读地图的参数
Map map = request.getParameterMap(); //Reading the Map //Works for GET && POST Method for(String paramName:map.keySet()) { String[] paramValues = map.get(paramName); //Get Values of Param Name for(String valueOfParam:paramValues) { //Output the Values System.out.println("Value of Param with Name "+paramName+": "+valueOfParam); } }
使用Java 8尝试资源:
StringBuilder stringBuilder = new StringBuilder(); try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()))) { char[] charBuffer = new char[1024]; int bytesRead; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } }
转载地址:http://nlggp.baihongyu.com/