Wednesday, 19 November 2008

Sending SMS via HTTP web service post with groovy

We use Groovy has our primary technique to plug in with web services and bring content into our mobile UIs. We picked Groovy for the development speed and for it’s clarity (perhaps beauty) of code that is created – essentially minimal code scaffolding that we get so used to in Java so that what we get down to coding business and application logic.

For a recent project we also used TextAnywhere to receive and send SMSs to people who wanted to interact with our quiz.

As a quick demonstration of why Groovy is so useful I thought I show you the Groovy code that uses this API to send SMSs compared with the (less than elegant) Java example provided by Textanywhere to use their SMS send API.

def conn = new URL(SEND_ENPOINT).openConnection()
conn.outputStream.withWriter("ASCII") { writer ->
  ].each {
    writer.write("&" + URLEncoder.encode(it.key,"UTF-8") +
      "=" + URLEncoder.encode(it.value,"UTF-8"))
sendResult = conn.inputStream.text

You gotta admit – that’s pretty readable and succinct. Read a bit more about Groovy closures and looping if you want learn how this works and get coding Groovy today.