HttpURLClient

HTTPURLClient is an alternate implementation that does not rely on HttpClient sockets for communication. The main motivation behind this is use in Google App Engine. GAE does not allow direct socket communication; instead web resources are accessed only via the HttpURLConnection class. Since HttpURLConnection is somewhat cumbersome to use (particularly for REST operations,) HttpURLClient applies some of HTTPBuilder's idioms on top of an HttpURLConnection.

HttpURLClient supports automatic content-type parsing and request marshalling, URI manipulation and the convenient header access.

Here is an example of accessing Twitter's REST interface, using both XML and JSON:

import groovyx.net.http.*

def http = new HttpURLClient( url: 'http://twitter.com/statuses/' )

// JSON request:
def resp = http.request( path: 'user_timeline.json',
        query: [id:'httpbuilder', count:5] )

println "JSON response: ${resp.status}"

resp.data.each {  // iterate over each JSON object in the response array:
    println it.created_at
    println '  ' + it.text
}

/* Slightly different request that returns XML; note that Twitter uses the path
   to determine if you want a response as XML or JSON: */

// JSON request:
def resp = http.request( path: 'user_timeline.xml',
        query: [id:'httpbuilder', count:5] )

println "\n\nXML response: ${resp.status}"

resp.data.status.each {  // iterate over each XML 'status' element in the response:
    println it.created_at.text()
    println '  ' + it.text.text()
}

Note that the example above can be run by adding the @Grab macro with Groovy 1.6+ to automatically download the HTTPBuilder libraries. See the download page for more details.