gpt4 book ai didi

groovy - 如何下载文件? - 常规

转载 作者:行者123 更新时间:2023-12-04 02:20:34 25 4
gpt4 key购买 nike

我需要下载一个文件(例如: https://www.betaseries.com/srt/391160 )所以我在网上找到了不同的方法:

def download(String remoteUrl, String localUrl)
{
def file = new FileOutputStream(localUrl)
def out = new BufferedOutputStream(file)
out << new URL(remoteUrl).openStream()
out.close()
}

或者
def download(String remoteUrl, String localUrl) {
new File("$localUrl").withOutputStream { out ->
new URL(remoteUrl).withInputStream { from -> out << from; }
}
}

我看到文件已创建,但文件大小始终等于 1KB,我该如何处理?

预先感谢,

本杰明

最佳答案

所以,它看起来像 url https://www.betaseries.com/srt/391160重定向到 http://www.betaseries.com/srt/391160 (http,不是 https)

所以你捕获的是重定向响应(1K)而不是完整的响应图像。

您可以这样做以获取实际图像:

def redirectFollowingDownload( String url, String filename ) {
while( url ) {
new URL( url ).openConnection().with { conn ->
conn.instanceFollowRedirects = false
url = conn.getHeaderField( "Location" )
if( !url ) {
new File( filename ).withOutputStream { out ->
conn.inputStream.with { inp ->
out << inp
inp.close()
}
}
}
}
}
}

关于groovy - 如何下载文件? - 常规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14474973/

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