如何下载文件? - Groovy [英] How to download a file? - Groovy
问题描述
我需要下载一个文件(例如: https://www.betaseries.com/ srt / 391160 ),所以我在网上找到了不同的方法:
I need to download a file (this one for example: https://www.betaseries.com/srt/391160) so I have found different methods on the web:
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我怎么能fx?
I see that the file is created but the file size is always equal to 1KB how can I fx it?
提前感谢
本杰明
推荐答案
所以,它看起来像url https://www.betaseries.com/srt/391160 重定向到 http: //www.betaseries.com/srt/391160 (http,而不是https)
So, it looks like the url https://www.betaseries.com/srt/391160 redirects to http://www.betaseries.com/srt/391160 (http, not https)
所以你抓住的是重定向响应(1K)
So what you're grabbing is the redirect response (1K) not the full response image.
您可以这样做来获取实际图像:
You can do this to get the actual image:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!