首页 > 解决方案 > Groovy URL getText() 返回一个 PasswordAuthentication 实例

问题描述

我正在尝试在 Jenkins 管道 Groovy 脚本中下载受密码保护的 Gerrit URL 的内容。HTTPBuilder 不可访问,因此我将 URL 类与 Authenticator 一起使用:

// To avoid pipline bailing out since data PasswordAuthentication is non-serializable
@NonCPS
def getToString(data) {
    data.toString()
}

def fetchCommit(host, project, version) {
    withCredentials([usernamePassword(credentialsId: 'my-credentials',
                                      usernameVariable: 'user',
                                      passwordVariable: 'PASSWORD')]) {
        proj = java.net.URLEncoder.encode(project, 'UTF-8')
        echo "Setting default authentication"
        Authenticator.default = {
            new PasswordAuthentication(env.user, env.PASSWORD as char[])
        } as Authenticator
        echo "https://${host}/a/projects/${proj}/commits/${version}"
        url = "https://${host}/a/projects/${proj}/commits/${version}".toURL()
        result = getToString(url.getText())
        echo "${result}"
    }
}

结果是 PasswordAuthentication 实例,而不是预期的数据:

[Pipeline] echo
java.net.PasswordAuthentication@3938b0f1

我一直在努力解决这个问题。我尝试了不同的方法来设置身份验证和读取数据,但大多数都以异常告终。在 url 上使用 eachLine() 根本不会进入闭包。这项工作也很快退出,给人的印象是它甚至没有尝试建立联系。

参考:

标签: authenticationjenkinsurljenkins-pipelinejenkins-groovy

解决方案


推荐阅读