【问题标题】:Getting the response for REST API using HTTPBuilder使用 HTTPBuilder 获取 REST API 的响应
【发布时间】:2016-05-25 14:31:56
【问题描述】:

我正在尝试调用 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
}

【问题讨论】:

    标签: json rest groovy httpbuilder


    【解决方案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
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-26
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多