W3docs

Get the POST request body from HttpServletRequest

To get the POST request body from an HttpServletRequest object in Java, you can use the getReader method of the ServletRequest interface to read the request body as a BufferedReader and then use the readLine method to read the data as a string.

To get the POST request body from an HttpServletRequest object in Java, you can use the getReader method of the ServletRequest interface to read the request body as a BufferedReader. For binary or non-UTF-8 payloads, getInputStream is often preferred.

Here is an example of how you can do this:


import java.io.BufferedReader;
import java.io.IOException;
import jakarta.servlet.ServletRequest; // Use javax.servlet for older Java EE versions

public class Main {
  // Conceptual demonstration: request is provided by the servlet container
  public static String getRequestBody(ServletRequest request) throws IOException {
    StringBuilder sb = new StringBuilder();
    try (BufferedReader reader = request.getReader()) {
      String line;
      while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
      }
    }
    return sb.toString();
  }
}

I hope this helps! Let me know if you have any other questions.