jgritman / httpbuilder

315 stars 154 forks source link

No way to extract response content in case of a HTTP failure ? #69

Closed Lucas-C closed 7 years ago

Lucas-C commented 7 years ago

Hi.

I had a look at what HttpResponseDecorator contains, but I don't see how to get the response body in case of a non-200 HTTP status :

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

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

new HTTPBuilder('https://echo.getpostman.com/status/404').request(GET, 'application/json') {
    response.success = { resp, json -> println "# Success !\n$json\n" }
    response.failure = { resp ->
        def resp_props = resp.properties.collect{it}.join('\n')
        println "# failure\n$resp_props\n"
    }
}

What I see is that data is null.

This is very limitating to bubble up error messages from HTTP services.

Is there a way to extract the JSON from getpostman.com response in this example ?

Regards.

kenwdelong commented 7 years ago

You can do something like this:

def failure = { resp -> 
    resp.entity.writeTo(System.out)
    println resp.statusLine.statusCode.toString()
}

Not the easiest, but it works.

I think that resp.entity is a BasicHttpEntity , but you can check that. writeTo() takes any OutputStream.

Lucas-C commented 7 years ago

Awesome, thanks ! I did this :

def failure = { resp ->
        def outputStream = new ByteArrayOutputStream()
        resp.entity.writeTo(outputStream)
        def errorMsg = outputStream.toString('utf8')
}