Groovy 为什么HTTPBuilder基本身份验证不起作用?

Groovy 为什么HTTPBuilder基本身份验证不起作用?,groovy,basic-authentication,httpbuilder,Groovy,Basic Authentication,Httpbuilder,以下代码不会对用户进行身份验证(不会发生身份验证失败,但由于缺乏权限,调用失败): 但以下方法很管用: def remote = new HTTPBuilder("http://example.com") remote.request(POST) { req -> uri.path = "/do-something" uri.query = ['with': "data"] headers.'Authorization' = "Ba

以下代码不会对用户进行身份验证(不会发生身份验证失败,但由于缺乏权限,调用失败):

但以下方法很管用:

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

为什么第一个没有工作?

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

有两件事我可以从脑海中想出来。

.setHeaders
方法需要映射。您是否尝试过“授权”:“基本${”用户名:密码.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
}

希望这有帮助

它是如何失败的?服务器应返回HTTP 401状态代码以触发基本身份验证。然后HttpBuilder将发送第二个带有授权头的请求。它就是不起作用。请求本身返回一条消息,表示用户没有执行该操作的权限。我可以将用户名和密码更改为完全无效的内容,同样的情况也会发生。这可能会解决您的问题—在兼容的服务器上也会出现故障
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
}