groovy - 使用身份验证下载文件

时间:2018-04-27 12:56:02

标签: http authentication groovy httprequest basic-authentication

我需要使用Groovy使用基本身份验证(提示浏览器询问您域名\用户名和密码的身份验证类型)下载文本文件。我想避免使用其他库,在Groovy中是否有任何可以做到的事情?

我目前的代码是:

new File("test.txt").withOutputStream { out ->
    def url = new URL(myurl).openConnection()

    def remoteAuth = "Basic " + "myusername:mypassword".bytes.encodeBase64()
    url.setRequestProperty("Authorization", remoteAuth);
    out << url.inputStream
}

但服务器回复401错误。我该怎么办?

1 个答案:

答案 0 :(得分:2)

Groovy使用java.net.Authenticator API。您可以使用java.net.Authenticator#setDefault提供默认Authenticator。可以找到BasicAuth用法的示例in another Answer

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});
相关问题