14 posts categorized "httpbuilder"

04/27/2009

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.

04/23/2009

Groovy Script: Use HTTP Builder to Check Web Server Type

With the help of some folks on the groovy-user mailing list, I wrote the following script to pull the server name header from an HTTP HEAD request. Mostly, I use this for verification purposes when setting ServerTokens to Prod on an apache server or when suppressing the tomcat server identity. The script uses Tom Nichols' HTTP Builder module for groovy. Running it is pretty straightforward as the script only takes one argument; enter the URL of the site you want to test. For example:

./checkServerType.groovy http://blogs.techstacks.com/

#!/usr/bin/env groovy

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.HEAD
import static groovyx.net.http.ContentType.TEXT

// create a new builder
def http = new HTTPBuilder( args[0] )

http.request( HEAD, TEXT ) {req ->
response.success = { resp ->
println " ${resp.getFirstHeader('Server')} "
}
response.failure = { resp ->
println "Server Response: ${resp.statusLine}"
}
}