Make a get request to a URI or URL

This example will show how to make a get request to a URI in groovy with HttpBuilder. HTTPBuilder provides an abstraction on top of apache HttpComponents which provides a low level set of components for interaction with HTTP and associated protocols. The HTTPBuilder api coupled with groovy makes it easy to fetch and parse information from a URL which is similar to a JavaScript ajax call. A comparable example we demonstrate how to make a get request with apache components in java.

Http request

In this snippet, a closure is defined with request information. You can set various pieces of the request or response such as headers, content type, paths and how to handle response behavior. We will specify the request method as a GET, content type as text, two closures to handle the response and location of groovy examples. The first closure to handle the response is to handle if it is a success and the second if the response fails. When the status code is 200 we will output response, content type and response contents text to the console. If it fails a message will appear with not found.

@Test
void make_get_request() {

    def http = new HTTPBuilder()

    http.request( 'http://www.leveluplunch.com', Method.GET, ContentType.TEXT ) { req ->

        uri.path = '/groovy/examples/'
        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'
        }
    }
}

Output

Got response: HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
<!DOCTYPE html><html class=no-js><head>
...
</script></body></html>

Convenience GET method

This snippet will show how to use the convenience method to perform an HTTP GET. Similar to above we will make a request to leveluplunch groovy examples while specifying the path and content type. Only major difference is we will output each header name/value and remove the response closure as the http.get method will only handle a successful response.

@Test
void make_shorthand_get_request() {

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

    http.get( path : '/groovy/examples/',
            contentType : ContentType.TEXT) { 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--------------------'
    }
}

Output

Response status: HTTP/1.1 200 OK
Headers: -----------
 Content-Type : text/html; charset=utf-8
 Content-Length : 2135
 Connection : keep-alive
 Date : Sat, 18 Oct 2014 18:30:26 GMT
 Cache-Control : max-age=2628000
 Content-Encoding : gzip
 Last-Modified : Sat, 18 Oct 2014 02:35:56 GMT
 ETag : "589ea3baf27b3a7e60ab06aa7a697fbf"
 Server : AmazonS3
 Age : 1181
 X-Cache : Hit from cloudfront
 Via : 1.1 7085b627a31b3454397d9dc961a11a65.cloudfront.net (CloudFront)
 X-Amz-Cf-Id : 4rFukMhGKEoaxE8ZMz2gvAs-5niXNHW8VloR34cA8CLEXB4NmRbRYg==
Response data: -----
....