bil*_*dev 3 groovy file download
我需要从安全的Web位置将文件存入我的应用程序的内存中.我有要捕获的文件的URL,但似乎无法解决安全问题.这是Cookbook示例页面中的代码:
def download(address)
{
def file = new FileOutputStream(address.tokenize("/")[-1])
def out = new BufferedOutputStream(file)
out << new URL(address).openStream()
out.close()
}
Run Code Online (Sandbox Code Playgroud)
这是我的"内存"版本的同一个函数应该返回文件内容的字节数组:
def downloadIntoMem(address)
{ // btw, how frickin powerful is Groovy to do this in 3 lines (or less)
def out = new ByteArrayOutputStream()
out << new URL(address).openStream()
out.toByteArray()
}
Run Code Online (Sandbox Code Playgroud)
当我针对一个不安全的URL(选择你可以在网上找到的任何图像文件)尝试这个时,它的工作正常.但是,如果我选择需要用户/密码的URL,则不要去.
好的,在这方面做了一些工作.似乎Authenticator方法确实有效,但是以一种全面的方式.第一次访问URL时,我得到一个302响应,其中包含一个登录服务器的位置.如果我使用Authenticator集访问该位置,那么我将获得另一个带有Cookie的302,并将该位置设置回原始URL.如果我然后访问原始,下载正确.
所以,我必须模仿一下浏览器,但最终它一切正常.
使这个社区维基,所以其他人可以添加其他方法.
谢谢!
Wan*_*tos 10
如果网址上的信用不起作用,您可以使用此功能.它适用于基本身份验证.
new File(localPath).withOutputStream { out ->
def url = new URL(remoteUrl).openConnection()
def remoteAuth = "Basic " + "${user}:${passwd}".bytes.encodeBase64()
url.setRequestProperty("Authorization", remoteAuth);
out << url.inputStream
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助!
| 归档时间: |
|
| 查看次数: |
5055 次 |
| 最近记录: |