You can take advantage of Groovy features like with(), improvements to URLConnection, and simplified getters/setters:
GET:
String getResult = new URL('http://mytestsite/bloop').text
POST:
String postResult
((HttpURLConnection)new URL('http://mytestsite/bloop').openConnection()).with({
requestMethod = 'POST'
doOutput = true
setRequestProperty('Content-Type', '...') // Set your content type.
outputStream.withPrintWriter({printWriter ->
printWriter.write('...') // Your post data. Could also use withWriter() if you don't want to write a String.
})
// Can check 'responseCode' here if you like.
postResult = inputStream.text // Using 'inputStream.text' because 'content' will throw an exception when empty.
})
Note, the POST will start when you try to read a value from the HttpURLConnection, such as responseCode
, inputStream.text
, or getHeaderField('...')
.
j = new groovy.json.JsonSlurper().parseText(new URL("https://httpbin.org/get").getText())
thenprintln j.headers["User-Agent"]
– Rikki@Grab
it makes http-builder fairly painless to use:@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7')
– Aloha