8

我需要下载一个文件(例如: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 我该如何修复它?

预先感谢,

本杰明

4

1 回答 1

10

因此,看起来 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()
          }
        }
      }
    }
  }
}
于 2013-01-23T10:22:53.960 回答