Wednesday, November 19, 2008

Reading HTTP Request Body in Servlet

Suppose you are writing a program using Java on Java EE platform to create a web application, dynamic web pages or Java Web Service, you probably come to the point that you need to read HTTP request body, especially if you want to use Servlet Filter to intercept and manipulate ServletRequest / HTTPServletRequest before it is served by targeted servlet / JSP.

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.

13 comments:

  1. BufferedReader buff = req.getReader();
    char[] buf = new char[4 * 1024];
    int len;
    while ((len = reader.read(buf, 0, buf.length)) != -1) {
    out.write(buf, 0, len);
    }

    In your code neither the "out" or the "reader" is defined. Did you mean to buff -> reader ? Also what type is out ?

    ReplyDelete
  2. Like your pic dude! Thats our Taj Mahal....:)
    Btw, thanks for the post...came in real handy!

    ReplyDelete
  3. @bendigi

    BufferedReader reader = buff;
    ServletOutputStream out = res.getOutputStream();

    ReplyDelete
  4. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    AWS Certification Training Online Toronto
    AWS Certification Training Online Newyork
    AWS Certification Training Online London

    ReplyDelete
  5. Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
    python training in chennai
    python course institute in chennai

    ReplyDelete
  6. Thanks for this amazing blog , it is very useful content for us
    keep sharing this type of informtion if anyone is looking for the best training institute in nodia visit us.

    Python Training Institute
    data science training in noida
    machine learning institute in noida
    java training institute in noida
    data science training in noida

    ReplyDelete
  7. Thanks for this amazing blog , it is very useful content for us
    keep sharing this type of informtion if anyone is looking for the best digital marketing training institute in ghaziabad visit us.
    https://theprimeinstitute.in/

    ReplyDelete