Java – Get the content of inputStream from HttpServletRequest

Recently, i got a support case and it is about the inconsistency of the content length declared in the http header and the actual content length of the http request.

So i modified an existing program which will get the http request and manipulate it. I add some codes such that it will get the request inputStream and count it byte by byte before the request manipulation.

Here comes to the problem. The inputStream has no mark support. If i count by reading it byte by byte, i cannot get it again for manipulation since it cannot be reset.

To solve the problem, i import the Apache Commons IO to the project and modify the code. This time, i convert the inputStream to string for counting. Then i create a new InputStream from the string for manipulation.

...

// Convert the request inputStream to string
String str_request = IOUtils.toString(request.getInputStream());

// Count the actual content length of the http request
char[] char_array_request = str_request.toCharArray();
int count = char_array_request.length;

// Create a inputStream for further manipulation
requestStream = new ByteArrayInputStream(str_request.getBytes());

...

Done =)

Thanks Steve Chan and Simon Ho.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.