Using Groovy’s HTTP Builder Library
In my Grails app project, I had a requirement to make an HTTP call from the server’s end. After a lot of searching, I found some old fashioned Java code to achieve what I was looking for. But I was looking for something more clean, concise and more importantly a groovier way of doing it. On searching a little bit more, I found the awesome feature of HTTPBuilder in Groovy – a simpler and cleaner way to make HTTP requests.
There are two different way to make an HTTP call using the HTTPBuilder class:
1) Using the “get” and “post” methods
HTTPBuilder class provides you with wrapper methods to make GET and POST calls easily to the URL of your choice. An example usage is given below:
[code]
String url = “http://www.example.com”
String uriPath = “/sample-rest-call
HTTPBuilder http = new HTTPBuilder(url)
http.get(path:uriPath, contentType: ContentType.TEXT, query: content) { resp, reader ->;
println reader.text
println resp.statusLine
}
http.post(path:uriPath, body:content, requestContentType:URLENC) { resp, reader ->;
//content will be url encoded
println reader.text
println resp.statusLine
assert resp.statusLine.statusCode == 200
}
[/code]
2) Using the “request” method
This method is internally called by the “get” and “post” methods discussed earlier. An example usage is given below:
[code]
String url = “http://www.example.com”
String uriPath = “/sample-rest-call
HTTPBuilder http = new HTTPBuilder(url)
http.request(POST, JSON) {
uri.path = uriPath
send URLENC, content
response.success = { resp, reader ->;
String jsonResponse = (reader.readLines().join() as String)
println new JsonSlurper().parseText(jsonResponse)
}
response.failure = { resp, reader ->;
log.error "Request failed : [URI : ${uriPath}, Status: ${resp.status}]"
}
response.’401’= {resp ->;
println “Status 401 received”
}
}
[/code]
As you can see in the above example, the HTTPBuilder provides a very nice DSL to deal with the general case of dealing with errors and also allows you to provide special handling for specific status codes like the 401 status code in the example given above.
You can find more in-depth documentation about the HTTPBuilder class at the following link:
Cool…KEep the copy pasting going..