Http Client in Groovy

Here’s the translation of the Go HTTP client example to Groovy, formatted in Markdown suitable for Hugo:

Our example demonstrates how to create a simple HTTP client using Groovy. We’ll use the groovyx.net.http.HTTPBuilder class, which provides excellent support for HTTP operations.

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.TEXT

def http = new HTTPBuilder('https://gobyexample.com')

http.request(GET, TEXT) { req ->
    response.success = { resp, reader ->
        println "Response status: ${resp.status}"
        
        def lines = reader.readLines()
        lines[0..4].each { line ->
            println line
        }
    }

    response.failure = { resp ->
        println "Request failed with status ${resp.status}"
    }
}

In this example, we’re using the HTTPBuilder class to issue an HTTP GET request to a server. The HTTPBuilder constructor takes the base URL as an argument.

We then use the request method to perform the GET request. The response.success closure is called if the request is successful. Here, we print the HTTP response status and the first 5 lines of the response body.

To run this Groovy script, save it to a file (e.g., http-client.groovy) and execute it using the groovy command:

$ groovy http-client.groovy
Response status: 200
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Go by Example</title>

This script demonstrates basic HTTP client functionality in Groovy. It shows how to make a GET request, handle the response, and process the response body.

Note that unlike the original example, Groovy’s HTTPBuilder handles the opening and closing of the connection automatically, so we don’t need to explicitly close it.

Also, error handling is done through the response.failure closure, which is called if the request fails. This replaces the need for explicit error checking as seen in the original example.