Search code examples
groovyhttpbuilder-ng

Response is always empty


I'm trying to execute a simple HTTP request:

@Grab(group='io.github.http-builder-ng', module='http-builder-ng-apache', version='1.0.4')
import groovyx.net.http.*

HttpBuilder http = HttpBuilder.configure {
    request.uri = 'https://stackoverflow.com'
    request.accept = ['text/html']
}

http.get {
    response.success { FromServer fromServer ->
        println("Got status $fromServer.statusCode $fromServer.message")
        println("Has body: $fromServer.hasBody")
        try {
            List<String> bodyLines = fromServer.reader.withReader { it.readLines() }
            String body = bodyLines.join("\n")
            if (body.empty) {
                println("Body is empty.")
            } else {
                println("Body: $body")
            }
        } catch (Exception e) {
            println("Reading successful response failed. $e")
        }
    }
}

The output is:

Got status 200 OK
Has body: true
Body is empty.

What's the secret to reading the response body? Groovy 2.5.19.


Solution

  • The response.success handler takes a BiFunction<FromServer,Object> as well where the second parameter is the body content object. If you add a second parameter to your success closure it should have the body content in it, e.g.

    response.success { FromServer fromServer, Object body -> 
        // your stuff
    }