13

The following code doesn't authenticate the user (no authentication failure happens, but the call fails due to lack of permissions):

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 ?: [:]
    }
}

But the following works fine:

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 ?: [:]
    }
}

Why isn't the first one working?

4

2 回答 2

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
}

希望这可以帮助

于 2016-11-16T05:07:29.543 回答
0

看起来您的服务器不是完全符合 HTTPBuilder 的。它应该返回 401 代码(这是 REST 服务器的标准行为,但对于其他服务器来说是非标准行为),以便 HTTPBuilder 捕获此状态并重新发送身份验证请求。这里是关于它的。

于 2015-09-20T16:02:52.200 回答