Groovy: Post to a URL

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.

Advertisement

5 responses to this post.

  1. 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.

    Reply

  2. Your snippet was a life saviour :)
    Thanks
    G

    Reply

  3. [...] Groovy: Post to a URL April 20094 comments 3 [...]

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.