Reading HTTP Body is easy. You can use either the following methods to get HTTP Request Body (HTTP Request Payload). Both methods is useful only with HTTP POST message. If you try to read HTTP GET body, you will not get anything (except a null String). This is because HTTP GET message has empty body.
getReader()
This method is defined in Interface ServletRequest. It returns a BufferedReader object. Here is an example on how to read HTTP Request Body using getReader() method.
// inside service(ServletRequest req, ServletResponse res)
// of a class that implements Servlet
// or
// inside doPost(HttpServletRequest req, HttpServletResponse resp)
// of a class that implements HTTPServlet
BufferedReader buff = req.getReader();
char[] buf = new char[4 * 1024]; // 4 KB char buffer
int len;
while ((len = reader.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, len);
}
getInputStream()
This method is defined in Interface ServletRequest. It returns ServletInputStream which is an InputStream object.
// inside service(ServletRequest req, ServletResponse res)
// of a class that implements Servlet
// or
// inside doPost(HttpServletRequest req, HttpServletResponse resp)
// of a class that implements HTTPServlet
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
String body = stringBuilder.toString();
System.out.println(body);
Note that by reading HTTP Request Body by using either of the above method, you cannot read the body again. Also, you can only call getReader() or getInputStream() only once and not both; otherwise you will get IllegalStateException.
If you want to use getReader() or getInputStream() in Filter to intercept, manipulate or reconstruct HTTP Request Body, you must use ServletRequestWrapper to reconstruct or preserve HTTP Request Body. See ServletRequestWrapper example here.