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

Noe*_*Yap 12 groovy basic-authentication httpbuilder

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

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 ?: [:]
    }
}
Run Code Online (Sandbox Code Playgroud)

但以下工作正常:

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 ?: [:]
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么不是第一个工作?

asm*_*dey 0

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