groovy post to a url

Published:
Welcome to the dim corner of the library, where fools rush in and angels fear to tread!

This blog post is ancient. If it is technical, the information is likely inaccurate, or at least out of date. If it is non-technical, it’s entirely possible that the relevant facts and my own opinions have changed significantly since it was written.

It is only preserved as part of this site’s permanent historical archive.

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.