HttpServletRequest get JSON POST data
To get JSON POST data 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 data = sb.toString();
// The 'data' string now contains the JSON POST data
}
}
Once you have the JSON POST data as a string, you can use a JSON library such as Jackson to parse it and access the individual fields.
I hope this helps! Let me know if you have any other questions.