If you’ve ever worked with the brilliant Recaptcha service, you’ll know that their REST API requires an HTTP POST rather than a GET. As I had only used GET requests thus far, I googled around and found a pretty easy solution:
private def evaluateCaptcha(def remoteIp, def challenge, def response) {
def config = recaptchaService.getRecaptchaConfig()
def urlString = "http://api-verify.recaptcha.net/verify"
def queryString = "privatekey=${config.recaptcha.privateKey}&remoteip=${remoteIp}&challenge=${challenge}&response=${URLEncoder.encode(response)}"
def url = new URL(urlString)
def connection = url.openConnection()
connection.setRequestMethod("POST")
connection.doOutput = true
def writer = new OutputStreamWriter(connection.outputStream)
writer.write(queryString)
writer.flush()
writer.close()
connection.connect()
def recaptchaResponse = connection.content.text
log.debug(recaptchaResponse)
recaptchaResponse.startsWith("true")
}
I have to credit Justin Spradlin for the code that ultimately got me here. Consider this a +1.








Posted by Dmitriy Kopylenko on April 26, 2009 at 9:19 pm
Check out Groovy’s RESTClient: http://mrhaki.blogspot.com/2009/03/use-restclient-to-post-and-read-xml.html
Posted by Matt on April 26, 2009 at 9:25 pm
Thanks, I’ll take a look!
Posted by Charlie Hubbard on May 5, 2009 at 3:37 pm
Well this was helpful in that it showed me Groovy api to URLs needs serious work. Groovy isn’t being much help here since this code is really the same as doing it in Java. It’s also not URL encoding the args. We really need something as elegant as get, but with post, and URL encoding.
“http://somehost/foo/bar/baz”.post( arg1: val1, arg2: val2, arg3: val3,…) { stream ->
// do something
}
Something simple like that.
Posted by Greg Gigon on January 29, 2010 at 7:31 pm
Your snippet was a life saviour
Thanks
G
Posted by 2010 in review: the automated analysis… « Matt Stine's Blog on January 2, 2011 at 8:28 pm
[...] Groovy: Post to a URL April 20094 comments 3 [...]