在Java servlet中从POST请求获取请求负载

我有一个JavaScript库发送一个POST请求到我的Java servlet,但在doPost方法,我似乎无法得到请求有效载荷的内容。 在Chrome开发者工具中,所有的内容都在头文件标签的Request Payload部分,内容就在那里,而且我知道doPost方法正在接收POST,但是它只是空白。

对于HttpServletRequest对象,我可以通过什么方式获取请求负载中的数据?

request.getParameter()request.getAttributes()都没有数据

使用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<String,String[]>

您可以阅读地图的参数

 Map<String, String[]> 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); } }