Groovy 如何下载文件?-棒极了

Groovy 如何下载文件?-棒极了,groovy,https,download,Groovy,Https,Download,我需要下载一个文件(例如:),因此我在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下载(字符

我需要下载一个文件(例如:),因此我在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下载(字符串remoteUrl,字符串localUrl)
{
def file=新文件输出流(本地URL)
def out=新的BufferedOutputStream(文件)
出来
新URL(remoteUrl)。使用InputStream{from->out时,URL看起来会重定向到(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()
          }
        }
      }
    }
  }
}
下载(字符串url、字符串文件名){ while(url){ 使用{conn-> conn.instanceFlowRedirects=false url=conn.getHeaderField(“位置”) 如果(!url){ 新文件(文件名).withOutputStream{out-> conn.inputStream.with{inp->
哦,太好了,我还没有看到这个重定向。非常感谢你的帮助!
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()
          }
        }
      }
    }
  }
}