如何获得Groovy RestClient失败响应的完整响应

时间:2015-03-03 23:20:11

标签: groovy rest-client

目前,我收到了HttpResponseException,它只有statusCode。 我怎样才能获得完整的回复?

这是我正在使用的代码

restClient = new RESTClient("http://${Server}")
try {
    HttpResponseDecorator resp = restClient.post(path,body,requestContentType)     
        as HttpResponseDecorator
    return JSONObject.fromObject(resp.getData()).get("topKey","");
    }
catch (HttpResponseException e) {
            error(e.toString())
    }

它只输出这个:

[oaf.error] groovyx.net.http.HttpResponseException: Internal Server Error

2 个答案:

答案 0 :(得分:5)

添加自定义失败的响应处理程序:

        restClient = new RESTClient("http://${Server}")
        restClient.handler.failure = { resp, data ->
            resp.setData(data)
            String headers = ""
            resp.headers.each {
                headers = headers+"${it.name} : ${it.value}\n"
            }
            throw new HttpResponseException(resp.getStatus(),"HTTP call failed. Status code: ${resp.getStatus()}\n${headers}\n"+
                                            "Response: "+(resp as HttpResponseDecorator).getData())
            return resp
        }

答案 1 :(得分:0)

实际上,您可以从抛出的异常中提取完整响应。例如,如果您捕获的异常为e且响应正文JSON应包含名为myCustomErrorCode的字段,则除了e.response.data.myCustomErrorCode之外,您还可以通过查看e.statusCode来检查其值。< / p>