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.
4 Responses
Dmitriy Kopylenko
26|Apr|2009 1Check out Groovy’s RESTClient: http://mrhaki.blogspot.com/2009/03/use-restclient-to-post-and-read-xml.html
Matt
26|Apr|2009 2Thanks, I’ll take a look!
Charlie Hubbard
05|May|2009 3Well 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.
Greg Gigon
29|Jan|2010 4Your snippet was a life saviour
Thanks
G
Leave a reply
Search
Speaking Engagements
Memphis/Mid-South Java User Group
Real Developers Read! - Delivering Value
January 21, 2010 - 6 PM
Memphis/Mid-South Java User Group
Polyglot OSGi
April 15, 2010 - 6 PM
The Lambda Lounge
St. Louis, MO
Polyglot OSGi
February 4, 2010 - 6 PM
Mid-South Software Symposium
April 23-25, 2010
Memphis, TN
Northern Virginia Software Symposium
April 30-May 2, 2010
Reston, VA
Twitter
follow mstine at http://twitter.com
Categories
Archives
Blogroll
Leader of the Memphis/Mid-South JUG
Pandora
Meta