I have a Filter that receives the HttpServletRequest and the request is a POST that consists of an xml that I need to read into my filter method. What is the best way to get the posted xml from the HttpServletRequest object.
HttpServletRequest and Request Body So when we're dealing with the HTTP requests, HttpServletRequest provides us two ways to read the request body - getInputStream and getReader methods. Each of these methods relies on the same InputStream.
There are two methods for reading the data in the body: getReader() returns a BufferedReader that will allow you to read the body of the request. getInputStream() returns a ServletInputStream if you need to read binary data.
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).
A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest .
That depends on how the client has sent it.
If it's been sent as the raw request body, then use ServletRequest#getInputStream()
:
InputStream xml = request.getInputStream();
// ...
If it's been sent as a regular application/x-www-form-urlencoded
request parameter, then use ServletRequest#getParameter()
:
String xml = request.getParameter("somename");
// ...
If it's been sent as an uploaded file in flavor of a multipart/form-data
part, then use HttpServletRequest#getPart()
.
InputStream xml = request.getPart("somename").getInputStream();
// ...
That were the ways supported by the standard servlet API. Other ways may require a different or 3rd party API (e.g. SOAP).
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