Monday, October 6, 2014

Stupid Simple POST/GET with Groovy HTTPBuilder

Advertise

I was frustrated as hell today finding examples on how to use HTTPBuilder to perform a simple POST and GET request in my Grails application.

I now have something that I can use. This code has a dependency on groovyx.net.http libraries. This is available without even thinking by including the Rest Plugin into your app.

grails-app/conf/BuildConfig.groovy plugins { ... runtime ":rest:0.7" ...

Here’s the code. I placed it in /src/groovy/com/berry/utils/ApiConsumer.groovy

src/groovy/com/berry/utils/ApiConsumer.groovy 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051package com.berry.utilsimport groovyx.net.http.HTTPBuilderimport groovyx.net.http.ContentTypeimport groovyx.net.http.Methodimport groovyx.net.http.RESTClientclass ApiConsumer { static def postText(String baseUrl, String path, query, method = Method.POST) { try { def ret = null def http = new HTTPBuilder(baseUrl) // perform a POST request, expecting TEXT response http.request(method, ContentType.TEXT) { uri.path = path uri.query = query headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4' // response handler for a success response code response.success = { resp, reader -> println "response status: ${resp.statusLine}" println 'Headers: -----------' resp.headers.each { h -> println " ${h.name} : ${h.value}" } ret = reader.getText() println 'Response data: -----' println ret println '--------------------' } } return ret } catch (groovyx.net.http.HttpResponseException ex) { ex.printStackTrace() return null } catch (java.net.ConnectException ex) { ex.printStackTrace() return null } } static def getText(String baseUrl, String path, query) { return postText(baseUrl, path, query, Method.GET) }}

With this new class, we can easily perform requests.

def url = "http://myexample.com"def path = "/path/to/api"def query = [ firstName: "Eric", lastName: "Berry", email: "[email protected]" ]// Submit a request via GETdef response = ApiConsumer.getText(url, path, query)// Submit a request via POSTdef response = ApiConsumer.postText(url, path, query)

I hope this helps.


No comments: