I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
JSON object literals are surrounded by curly braces {}. JSON object literals contains key/value pairs. Keys and values are separated by a colon. Keys must be strings, and values must be a valid JSON data type: string.
ServletRequest provides basic setter and getter methods for requesting a Servlet, but it doesn't specify how to communicate. HttpServletRequest extends the Interface with getters for HTTP-communication (which is of course the most common way for communicating since Servlets mostly generate HTML).
To obtain the request body you have to call getInputStream() . But again, this will make the inputStream unavailable to other filters and the handler.
are you looking for this ?
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuilder sb = new StringBuilder(); BufferedReader reader = request.getReader(); try { String line; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } finally { reader.close(); } System.out.println(sb.toString()); }
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With