Skip to content
Tim Yates edited this page Apr 9, 2015 · 1 revision

HTTPBuilder defines a post() convenience method, which allows for easily POSTing data as an HTML form:

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.URLENC
 
def http = new HTTPBuilder( 'http://restmirror.appspot.com/' )
def postBody = [name: 'bob', title: 'construction worker'] // will be url-encoded
 
http.post( path: '/', body: postBody,
           requestContentType: URLENC ) { resp ->
 
  println "POST Success: ${resp.statusLine}"
  assert resp.statusLine.statusCode == 201
}

Similar to the get(...) convenience method, post(...) accepts the options as named parameters, and takes a closure that is called as the 'success' response handler. There is also a post variant that does not require a response handler closure; in this case, the builder instance's success handler is used, which by default will return the parsed response data.

Note on the Content-Type of POSTed data: HTTPBuilder's post method is special in particular because it assumes the request body will be URL-encoded form data. This is the only method that assumes a particular request content-type. For all methods that send a request body (including post,) a requestContentType parameter may be set to explicitly define how the request data should be serialized. In these cases, if the request content-type is not specified, it will default to the response contentType. Supported request content-types are handled by the EncoderRegistry class.

POSTing with the request(...) Method

This example is equivalent to the above, using the request() method:

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
 
def http = new HTTPBuilder('http://restmirror.appspot.com/')
http.request( POST ) {
    uri.path = '/'
    requestContentType = URLENC
    body =  [name: 'bob', title: 'construction worker']
 
    response.success = { resp ->
        println "POST response status: ${resp.statusLine}"
        assert resp.statusLine.statusCode == 201
    }
}

In the above example, uri, body, requestContentType and response are properties of the closure delegate so they are already defined.

For cases where the request content-type is necessarily different than the response, the request configuration delegate has a send() method which can be used set the request content-type and data at the same time:

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
 
def http = new HTTPBuilder('http://restmirror.appspot.com/')
http.request( POST ) {
    uri.path = '/'
    send URLENC, [name: 'bob', title: 'construction worker']
 
    response.success = { resp ->
        println "POST response status: ${resp.statusLine}"
        assert resp.statusLine.statusCode == 201
    }
}
Clone this wiki locally