使用HTTPBuilder获取REST API的响应

时间:2016-05-25 14:31:56

标签: json rest groovy httpbuilder

我正在尝试调用get方法(HttpGetJson)来返回响应值并使用它来获取resp(用于响应代码)和json(用于内容)值。但是只有当我从response.success中分别返回resp和json时才会得到有效的输出。如果我尝试返回响应对象,我只会得到NULL。是否有任何方式可以返回响应。

public static Object HttpGetJson(String url, String path)
        def http = new HTTPBuilder(url)

        //perform a GET request, expecting JSON response
        http.request(GET,JSON) { req ->
            uri.path = path

            //response handler for a success response code
            response.success = { resp, json ->
                return response//using response instead of json or resp returns null
            }
        }

public void testGET()
{

    def url = 'testurl'
    def path = 'testpath'

    //submit a request through GET
    def response1 = HttpUtils.HttpGetJson(url,path)

    println response1
    //println response.statusLine.statusCode
}

1 个答案:

答案 0 :(得分:1)

您可以使用return [resp: resp, json: json]返回两者的地图。

IMO你应该传递一个从response.success执行的闭包:

static HttpGetJson(String url, String path, Closure success) {
    def http = new HTTPBuilder(url)

    //perform a GET request, expecting JSON response
    http.request(GET,JSON) { req ->
        uri.path = path

        //response handler for a success response code
        response.success = success
    }
}

void testGET() {
    def url = 'testurl'
    def path = 'testpath'

    //submit a request through GET
    def response1 = HttpUtils.HttpGetJson(url,path) { resp, json ->
        println resp
        println json
    }

}