9

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()
}

or

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

I see that the file is created but the file size is always equal to 1KB how can I fx it?

Thank in advance,

Benjamin

1 Answer 1

11

So, it looks like the url https://www.betaseries.com/srt/391160 redirects to http://www.betaseries.com/srt/391160 (http, not https)

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()
          }
        }
      }
    }
  }
}
1
  • Oh super I haven't see this redirection. Thanks a lot for your help!
    – Kapoue
    Jan 23, 2013 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.