JavaHacker
JavaHacker

Reputation: 33

Java: Getting parameters and body from a HTTP POST

I want to read post parameters and the body from a http post.

Example: If you post to the url: http://localhost/controller?sign=true. In the post there is also json data in the body.

{"transaction": 
    {"user":[
        {"name": "Anna"}]
    }
}

Getting the parameter is done via public java.lang.String getParameter(java.lang.String name)

And the body can be retrieved via public ServletInputStream getInputStream() throws java.io.IOException

But how do you get in hold of both the parameter and the body? Because if i call getParameter before getInputStream the result will be -1 on the inputStream.

Upvotes: 0

Views: 3235

Answers (1)

Haz
Haz

Reputation: 2679

I believe under the covers of getParameter(String name), the ServletInputStream is being read to get those parameter. If you're going to be mixing POST data with URL parameters (I'm assuming the sign=true is the parameters you mentioned trying to get) use HttpServletRequest.getQueryString() to get the URL parameters, then you should still be able to read the body with getInputStream(). You will probably have to parse through the query string to get the information you're looking for, however.

EDIT: I forgot to add in my original answer that when the ServletInputStream is read, it cannot be read again. If the data from the stream needs to be used multiple times, you'll have to store it.

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html

Upvotes: 1

Related Questions