Http groovy-下载带有身份验证的文件
我需要使用Groovy下载一个使用基本身份验证(这种身份验证会提示浏览器向您询问域\用户名和密码)的文本文件。我希望避免使用额外的库,Groovy中没有任何东西可以做到这一点吗 我目前的代码是:Http groovy-下载带有身份验证的文件,http,authentication,groovy,httprequest,basic-authentication,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"
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
}
新文件(“test.txt”).withOutputStream{out->
def url=newurl(myurl).openConnection()
def remoteAuth=“Basic”+“myusername:mypassword”.bytes.encodeBase64()
setRequestProperty(“授权”,remoteAuth);
outGroovy使用java.net.Authenticator
API。您可以使用提供默认的Authenticator
。可以找到基本用法的示例
Groovy使用java.net.Authenticator
API。您可以使用提供默认的Authenticator
。可以找到基本用法的示例
非常感谢,这立即生效!我从代码中删除了两行验证代码并添加了您的。非常感谢,这立即生效!我从代码中删除了两行验证代码并添加了您的。
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});