groovy-下载带有身份验证的文件

use*_*769 1 authentication groovy http 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
}
Run Code Online (Sandbox Code Playgroud)

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

Men*_*ene 5

Groovy使用java.net.AuthenticatorAPI。您可以Authenticator使用 提供默认值java.net.Authenticator#setDefault。一个BasicAuth用法的示例可以在另一个Answer中找到。

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});
Run Code Online (Sandbox Code Playgroud)