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://twitter.com/statuses/' )
// auth omitted...
def postBody = [status:'update!',source:'httpbuilder'] // will be url-encoded
http.post( path: 'update.xml', body: postBody,
requestContentType: URLENC ) { resp ->
println "Tweet response status: ${resp.statusLine}"
assert resp.statusLine.statusCode == 200
}
(Note that the above example excludes some authentication details needed by the Twitter API; see the unit test for a working example.)
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.
This example is equivalent to the above, using the request() method:
import groovyx.net.http.HTTPBuilder
def http = new HTTPBuilder('http://twitter.com/statuses/')
// auth omitted...
http.request( POST ) {
uri.path = 'update.xml'
body = [ status : 'update!' , source : 'httpbuilder' ]
requestContentType = ContentType.URLENC
response.success = { resp ->
println "Tweet response status: ${resp.statusLine}"
assert resp.statusLine.statusCode == 200
}
}
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.URLENC
def http = new HTTPBuilder('http://twitter.com/statuses/')
// auth omitted...
http.request( POST ) {
uri.path = 'update.xml'
send URLENC, [ status : 'update!' , source : 'httpbuilder' ]
response.success = { .... }
}