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).
01.
#!/usr/bin/env groovy
02.
//USAGE: pretty straightforward--just run ./httpGetTest.groovy $URL
03.
import
groovyx.net.http.HTTPBuilder
04.
import
static
groovyx.net.http.Method.GET
05.
import
static
groovyx.net.http.ContentType.HTML
06.
07.
// create a new builder
08.
def
http =
new
HTTPBuilder( args[
0
] )
09.
http.request(GET,HTML) { req ->
10.
headers.
'User-Agent'
=
'GroovyHTTPBuilderTest/1.0'
11.
headers.
'Referer'
=
'http://blog.techstacks.com/'
12.
13.
// Switch to Java to set socket timeout
14.
req.getParams().setParameter(
"http.socket.timeout"
,
new
Integer(
5000
))
15.
16.
// Back to Groovy
17.
response.success = { resp, html ->
18.
println
"Server Response: ${resp.statusLine}"
19.
println
"Server Type: ${resp.getFirstHeader('Server')}"
20.
println
"Title: ${html.HEAD.TITLE.text()}"
21.
}
22.
response.failure = { resp ->
23.
println
resp.statusLine
24.
}
25.
}
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.