作者:萍子WYP | 来源:互联网 | 2022-12-19 11:53
我需要使用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 <
但是服务器回复401错误。我该怎么办?
1> Mene..:
Groovy使用java.net.Authenticator
API。您可以Authenticator
使用 提供默认值java.net.Authenticator#setDefault
。一个BasicAuth用法的示例可以在另一个Answer中找到。
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});