[英]Getting the response for REST API using 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
}
您可以同時返回兩者的地圖,例如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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.