gpt4 book ai didi

file - Groovy 中的安全文件下载

转载 作者:行者123 更新时间:2023-12-04 23:56:41 24 4
gpt4 key购买 nike

我需要从安全的网络位置将文件放入我的应用程序的内存中。我有要捕获的文件的 URL,但似乎无法解决安全问题。这是来自 Cookbook samples page 的代码:

def download(address)
{
def file = new FileOutputStream(address.tokenize("/")[-1])
def out = new BufferedOutputStream(file)
out << new URL(address).openStream()
out.close()
}

这是我的同一个函数的“内存”版本,它应该返回文件内容的字节数组:
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()
}

当我针对不安全的 URL 尝试此操作时(选择您可以在网上找到的任何图像文件),它工作得很好。但是,如果我选择需要用户/密码的 URL,则不行。

好的,在这方面做了更多的工作。似乎Authenticator方法 是否工作,但以一种迂回的方式。第一次访问 URL 时,我收到一个 302 响应,其中包含登录服务器的位置。如果我使用 Authenticator 集访问该位置,那么我会得到另一个带有 Cookie 的 302,并且该位置设置回原始 URL。如果我随后访问原始文件,则下载正确进行。

所以,我必须模拟一下浏览器,但最终一切正常。

将此作为社区维基,以便其他人可以添加其他方法。

谢谢!

最佳答案

如果 url 上的信用不起作用,您可以使用它。它适用于基本身份验证。

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
}

希望有帮助!

关于file - Groovy 中的安全文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/347325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com