« Groovy 1.6.2 Released | Main | BigIP: Enabling SSLv2 »


Groovy Script: HTTP Builder Get Example

Similar to the HTTP HEAD example from a few days ago, this script uses the Groovy HTTP Builder module to do a basic HTTP GET on a web page and does some very basic HTML parsing to display the title (to prove that it worked).

#!/usr/bin/env groovy
//USAGE: pretty straightforward--just run ./httpGetTest.groovy $URL
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.HTML

// create a new builder
def http = new HTTPBuilder( args[0] )
  http.request(GET,HTML) { req ->
    headers.'User-Agent' = 'GroovyHTTPBuilderTest/1.0'
    headers.'Referer' = 'http://blog.techstacks.com/'

// Switch to Java to set socket timeout
    req.getParams().setParameter("http.socket.timeout", new Integer(5000))

// Back to Groovy
  response.success = { resp, html ->
  println "Server Response: ${resp.statusLine}"
  println "Server Type: ${resp.getFirstHeader('Server')}"
  println "Title: ${html.HEAD.TITLE.text()}"
  response.failure = { resp ->
    println resp.statusLine

This script also highlights some of the mixing of java and groovy one can do within the same piece of code. Setting HTTP Client Parameters currently can only be done in Java. The code that sets the socket-timeout to 5 seconds above is java, the rest of the script is groovy.

This script and the previously posted HEAD sample will be modified further over the course of the next few weeks as I add some additional functionality and figure out how to better handle exceptions.


TrackBack URL for this entry:

Listed below are links to weblogs that reference Groovy Script: HTTP Builder Get Example: