Simplified GET Request

HTTPBuilder has convenience methods for GET and POST methods. Here is a simple HTTP GET which parses the response as a DOM object:

def http = new HTTPBuilder('http://www.google.com')

def html = http.get( path : '/search', query : [q:'Groovy'] )

assert html instanceof groovy.util.slurpersupport.GPathResult
assert html.HEAD.size() == 1
assert html.BODY.size() == 1

In the above example, we are making a request, and automatically parsing the HTML response based on the response's content-type header. The HTML stream is normalized (thanks to Neko,) and then parsed by an XmlSlurper for easy DOM traversal.

We are also taking advantage of HTTPBuilder's default success handler since we're not supplying a 'success' response handler closure. The default handler defined by HTTPBuilder (which can be overridden) simply returns the parsed response data.

Next is another GET request, with custom response-handling logic that prints the response to System.out:

def http = new HTTPBuilder('http://www.google.com')

http.get( path : '/search',
          contentType : TEXT,
          query : [q:'Groovy'] ) { resp, reader ->

  println "response status: ${resp.statusLine}"
  println 'Headers: -----------'
  resp.headers.each { h ->
    println " ${h.name} : ${h.value}"
  }
  println 'Response data: -----'
  System.out << reader
  println '\n--------------------'
}

In this version, the get() method also accepts a closure, which is interpreted as the 'success' response handler. A failure response (i.e. status code of 400 or greater) is still handled by the builder's default failure handler.

Additionally, we are telling HTTPBuilder to parse the response as ContentType.TEXT - which is a built-in type, handled by the default ParserRegistry to automatically create a Reader from the response data.

GET using the request() method

HTTPBuilder supports a generic request method that can be used to configure the request in a fine-grained manner.

def http = new HTTPBuilder()

http.request( 'http://ajax.googleapis.com', GET, TEXT ) { req ->
  uri.path = '/ajax/services/search/web'
  uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
  headers.'User-Agent' = "Mozilla/5.0 Firefox/3.0.4"
  headers.Accept = 'application/json'

  response.success = { resp, reader ->
    assert resp.statusLine.statusCode == 200
    println "Got response: ${resp.statusLine}"
    println "Content-Type: ${resp.headers.'Content-Type'}"
    println reader.text
  }

  response.'404' = {
    println 'Not found'
  }
}

In the above example, a 'request configuration closure' is defined as the final argument to the request method. This closure allows fine-grained configuration of the request and response handling behavior. Within the closure, there are a number of properties available via the closure's delegate. req is an instance of HttpRequest to directly access the Apache HttpClient API.