Groovy Script: HTTP Builder Get Example - Blogging Techstacks
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 groovy02.//USAGE: pretty straightforward--just run ./httpGetTest.groovy $URL03.importgroovyx.net.http.HTTPBuilder04.importstaticgroovyx.net.http.Method.GET05.importstaticgroovyx.net.http.ContentType.HTML06.07.// create a new builder08.defhttp =newHTTPBuilder( 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 timeout14.req.getParams().setParameter("http.socket.timeout",newInteger(5000))15.16.// Back to Groovy17.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.printlnresp.statusLine24.}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.
浙公网安备 33010602011771号