This example will show how to make a get request to a URI in groovy with HttpBuilder. HTTPBuilder provides an abstraction on top of apache HttpComponents which provides a low level set of components for interaction with HTTP and associated protocols. The HTTPBuilder api coupled with groovy makes it easy to fetch and parse information from a URL which is similar to a JavaScript ajax call. A comparable example we demonstrate how to make a get request with apache components in java.
Http request
In this snippet, a closure is defined with request information. You can set various pieces of the request or response such as headers, content type, paths and how to handle response behavior. We will specify the request method as a GET, content type as text, two closures to handle the response and location of groovy examples. The first closure to handle the response is to handle if it is a success and the second if the response fails. When the status code is 200 we will output response, content type and response contents text to the console. If it fails a message will appear with not found.
Output
Convenience GET method
This snippet will show how to use the convenience method to perform an HTTP GET. Similar to above we will make a request to leveluplunch groovy examples while specifying the path and content type. Only major difference is we will output each header name/value and remove the response closure as the http.get method will only handle a successful response.