Friday, October 8, 2010

Google API Authentication in Groovy

Here is the sample which you can use to create Google API authentication token from Groovy.

static String createAuthToken(){
def url = new java.net.URL("https://www.google.com/accounts/ClientLogin")
def connection = url.openConnection()
def queryString = "Email=${email}&Passwd=${pass}" +
"&service=reader&source=${servicename}"
def returnMessage = processRequest(connection, queryString)
if(returnMessage != null){
return returnMessage.split(/Auth=/)[1].trim()
}
}

static String processRequest(connection, dataString){
connection.setRequestMethod("POST")
connection.doOutput = true
Writer writer = new OutputStreamWriter(connection.outputStream)
writer.write(dataString)
writer.close()
connection.connect()
try {
def reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
return reader.text
} catch (RuntimeException e) {
return null;
}
}

def readContent() {
def url = new java.net.URL("http://www.google.com/reader/api/0/" + service)
def connection = url.openConnection()
def content = processRequest(connection, input)
...
}