Monday, October 28, 2013

Grails get post/put raw request body

There may be situation where the data in body for the request is need to be read. To read the raw data:
request.getReader().text

However, this will give the following error:
getInputStream() has already been called for this request

This is because the default request parser needs to be turned off before reading the body text. Here is one way how to do it in the grails-app/conf/UrlMapping:
class UrlMappings {
    static mappings = {
        "/api/review/$id?"(controller: 'review', parseRequest: false){
            action = [ PUT: "update", POST: "save", GET: "show"]
        }
...
}
By specifying ‘parseRequests: false’ in highlighted line, it will turn off the Grails automatic parsing and make it possible to read the body data (i.e. request.getReader().text)

You can read request body in your filters before method and parse if need as you wish.
 

No comments:

Post a Comment