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.
Here is an example of how you can do this:
import java.io.BufferedReader;
import javax.servlet.ServletRequest;
public class Main {
public static void main(String[] args) throws Exception {
ServletRequest request; // Assume this is an HttpServletRequest object
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String requestBody = sb.toString();
// The 'requestBody' string now contains the POST request body
}
}
I hope this helps! Let me know if you have any other questions.