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

7

目前,我得到了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个回答

7

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

        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())
        }

我觉得很奇怪,resp中没有包含data,因为resp.setData()是一个非公共方法。 - jaco0646

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接