使用 HTTPBuilder 获取 REST API 的响应

Getting the response for REST API using HTTPBuilder

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

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
}

你可以 return 一张同时包含两者的地图,比如 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
    }

}