coderberry

Stupid Simple POST/GET With Groovy HTTPBuilder

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
1
2
3
4
    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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.berry.utils

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.Method
import groovyx.net.http.RESTClient

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

1
2
3
4
5
6
7
8
9
def url = "http://myexample.com"
def path = "/path/to/api"
def query = [ firstName: "Eric", lastName: "Berry", email: "[email protected]" ]

// Submit a request via GET
def response = ApiConsumer.getText(url, path, query)

// Submit a request via POST
def response = ApiConsumer.postText(url, path, query)

I hope this helps.

Comments