Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file? - Groovy

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

like image 424
Kapoue Avatar asked Jan 23 '13 08:01

Kapoue


People also ask

How do I set the path of a file in groovy?

Since the path changes machine to machine, you need to use a variable / project level property, say BASE_DIRECTORY, set this value according to machine, here "/home/vishalpachupute" and rest of the path maintain the directory structure for the resources being used. Regards, Rao.


1 Answers

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()
          }
        }
      }
    }
  }
}
like image 198
tim_yates Avatar answered Oct 03 '22 16:10

tim_yates