Groovy HttpBuilder - Get Body Of Failed Response

喜夏-厌秋 提交于 2019-12-04 09:29:35

问题


I am trying to use the Groovy HTTPBuilder to write an integration test that will verify a correct error message is returned in the body along with an HTTP 409 status message. However, I can't figure out how to actually access the body of the HTTP response in failure cases.

http.request(ENV_URL, Method.POST, ContentType.TEXT) {
    uri.path = "/curate/${id}/submit"
    contentType = ContentType.JSON
    response.failure = { failresp_inner ->
        failresp = failresp_inner
    }
}

then:
assert failresp.status == 409
// I would like something like 
//assert failresp.data == "expected error message"

This is what the HTTP response from the server looks like:

2013-11-13 18:17:58,726 DEBUG  wire - << "HTTP/1.1 409 Conflict[\r][\n]"
2013-11-13 18:17:58,726 DEBUG  wire - << "Date: Wed, 13 Nov 2013 23:17:58 GMT[\r][\n]"
2013-11-13 18:17:58,726 DEBUG  wire - << "Content-Type: text/plain[\r][\n]"
2013-11-13 18:17:58,726 DEBUG  wire - << "Transfer-Encoding: chunked[\r][\n]"
2013-11-13 18:17:58,727 DEBUG  wire - << "[\r][\n]"
2013-11-13 18:17:58,728 DEBUG  wire - << "E[\r][\n]"
2013-11-13 18:17:58,728 DEBUG  wire - << "expected error message"
2013-11-13 18:17:58,728 DEBUG  wire - << "[\r][\n]"
2013-11-13 18:17:58,728 DEBUG  wire - << "0[\r][\n]"
2013-11-13 18:17:58,728 DEBUG  wire - << "[\r][\n]"

回答1:


I was recently just struggling with this while trying to integration test my REST endpoints using Spock. I used Sam's answer as inspiration and ended up improving on it so as to continue leveraging the auto-casting that HttpBuilder provides. After messing around for a while, I had the bright idea of just assigning the success handler closure to the failure handler to standardize the behavior regardless of what status code is returned.

client.handler.failure = client.handler.success

An example of it in action:

...

import static org.apache.http.HttpStatus.*

...

private RESTClient createClient(String username = null, String password = null) {
    def client = new RESTClient(BASE_URL)
    client.handler.failure = client.handler.success

    if(username != null)
        client.auth.basic(username, password)

    return client
}

...

def unauthenticatedClient = createClient()
def userClient = createClient(USER_USERNAME, USER_PASSWORD)
def adminClient = createClient(ADMIN_USERNAME, ADMIN_PASSWORD)

...

def 'get account'() {
    expect:
    // unauthenticated tries to get user's account
    unauthenticatedClient.get([path: "account/$USER_EMAIL"]).status == SC_UNAUTHENTICATED

    // user gets user's account
    with(userClient.get([path: "account/$USER_EMAIL"])) {
        status == SC_OK
        with(responseData) {
            email == USER_EMAIL
            ...
        }
    }

    // user tries to get user2's account
    with(userClient.get([path: "account/$USER2_EMAIL"])) {
        status == SC_FORBIDDEN
        with(responseData) {
            message.contains(USER_EMAIL)
            message.contains(USER2_EMAIL)
            ...
        }
    }

    // admin to get user's account
    with(adminClient.get([path: "account/$USER_EMAIL"])) {
        status == SC_OK
        with(responseData) {
            email == USER_EMAIL
            ...
        }
    }
}



回答2:


Does it work if you use:

response.failure = { resp, reader ->
    failstatus = resp.statusLine
    failresp   = reader.text
}



回答3:


I also struggled with this when I started using HttpBuilder. The solution I came up with was to define the HTTPBuilder success and failure closures to return consistent values like this:

HTTPBuilder http = new HTTPBuilder()
http.handler.failure = { resp, reader ->
    [response:resp, reader:reader]
}
http.handler.success = { resp, reader ->
    [response:resp, reader:reader]
}

Thusly defined, your HTTPBuilder instance will consistently return a map containing a response object (an instance of HttpResponseDecorator) and a reader object. Your request would then look like this:

def map = http.request(ENV_URL, Method.POST, ContentType.TEXT) {
    uri.path = "/curate/${id}/submit"
    contentType = ContentType.JSON
}

def response = map['response']
def reader = map['reader']

assert response.status == 409

The reader will be some kind of object that'll give you access to the response body, the type of which you can determine by calling the getClass() method:

println "reader type: ${reader.getClass()}"

The reader object's type will be determined by the Content-Type header in the response. You can tell the server specifically what you'd like returned by adding an "Accept" header to the request.



来源:https://stackoverflow.com/questions/19966548/groovy-httpbuilder-get-body-of-failed-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!