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).

view source

print?

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.

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。