2013-01-23 17 views
3

我需要下載一個文件(這一個例子:https://www.betaseries.com/srt/391160)所以我在網上找到了不同的方法:如何下載文件? - Groovy的

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我該怎麼辦?

預先感謝,

本傑明

回答

5

所以,它看起來像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() 
      } 
     } 
     } 
    } 
    } 
} 
+0

哦,超我還沒有看到這種重定向。 非常感謝您的幫助! – user2003035