以下代码未对用户进行身份验证(未发生身份验证失败,但由于缺少权限,调用失败):
def remote = new HTTPBuilder("http://example.com")
remote.auth.basic('username', 'password')
remote.request(POST) { req ->
uri.path = "/do-something"
uri.query = ['with': "data"]
response.success = { resp, json ->
json ?: [:]
}
}
但以下工作正常:
def remote = new HTTPBuilder("http://example.com")
remote.request(POST) { req ->
uri.path = "/do-something"
uri.query = ['with': "data"]
headers.'Authorization' =
"Basic ${"username:password".bytes.encodeBase64().toString()}"
response.success = { resp, json ->
json ?: [:]
}
}
为什么不是第一个工作?
答案 0 :(得分:1)
我能想到的两件事情就是我的头脑。
.setHeaders
方法需要地图。您是否尝试过'Authorization' : "Basic ${"username:password".bytes.encodeBase64().toString()}"
?
如果没有,那就是更多的工作和代码,但你也可以使用URIBuilder
。通常我封装到不同的类
protected final runGetRequest(String endpointPassedIn, RESTClient Client){
URIBuilder myEndpoint = new URIBuilder(new URI(Client.uri.toString() + endpointPassedIn))
HttpResponseDecorator unprocessedResponse = Client.get(uri: myEndpoint) as HttpResponseDecorator
def Response = unprocessedResponse.getData() as LazyMap
return Response
}
希望这有帮助