Skip to content

Instantly share code, notes, and snippets.

@webdevwilson
Created September 30, 2011 16:49
Show Gist options
  • Save webdevwilson/1254328 to your computer and use it in GitHub Desktop.
Save webdevwilson/1254328 to your computer and use it in GitHub Desktop.
A groovy script to send HTTP requests
def echo = System.out.&println
def url = new URL('%YOUR_URL_HERE%')
def conn = url.openConnection()
conn.useCaches = false
conn.doInput = true
conn.doOutput = true
def formData = """\
var1:blah
var2:blah
"""
// set headers
def headers = """\
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1
"""
if(formData) {
conn.requestMethod = 'POST'
formData = formData.split("\n")*.split(':').collect{ "${it[0]}=${it.length > 1 ? it[1] : ''}" }.join('&')
headers += "Content-Length:${formData.bytes.length}\nContent-Type:application/x-www-form-urlencoded"
}
echo 'Request Headers:'
headers.split("\n")*.split(':').each { echo "${it[0]}: ${it[1]}"; conn.setRequestProperty( it[0], it[1] ) }
echo ''
if(formData) {
echo 'POST Content'
echo formData
new DataOutputStream(conn.outputStream).withStream { s -> s.writeBytes formData }
echo ''
}
echo 'Response Headers:'
def responseHeaders = [:]
for (int i=0; ; i++) {
def name = conn.getHeaderFieldKey(i);
def value = conn.getHeaderField(i);
if (name == null && value == null) {
break;
}
if (name == null) {
echo value
} else {
echo name + ": " + value
responseHeaders[name] = value
}
}
echo ''
if(responseHeaders['Content-Type'].startsWith('text')) {
echo 'Response Body:'
def max = 180
conn.inputStream.eachLine { echo it }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment