我需要使用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错误。我该怎么办?
答案 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());
}
});