SP.
SP.

Reputation: 95

Download a zip file using Groovy

I need to download a zip file from a url using groovy.

Test url: https://gist.github.com/daicham/5ac8461b8b49385244aa0977638c3420/archive/17a929502e6dda24d0ecfd5bb816c78a2bd5a088.zip

What I've done so far:

def static downloadArtifacts(url,filename) {
        new URL(url).openConnection().with { conn ->
            conn.setRequestProperty("PRIVATE-TOKEN", "xxxx")
            url = conn.getHeaderField( "Location" )
            if( !url ) {
                new File((String)filename ).withOutputStream { out ->
                    conn.inputStream.with { inp ->
                        out << inp
                        inp.close()
                    }
                }
            }
        }
    }

But while opening the downloaded zip file I get an error "An error occurred while loading the archive".

Any help is appreciated.

Upvotes: 1

Views: 4433

Answers (3)

tanto wi
tanto wi

Reputation: 1

You can do it: 
    
import java.util.zip.ZipEntry
    import java.util.zip.ZipOutputStream
    class SampleZipController {
        def index() { }
        def downloadSampleZip() {
            response.setContentType('APPLICATION/OCTET-STREAM')
            response.setHeader('Content-Disposition', 'Attachment;Filename="example.zip"')
            ZipOutputStream zip = new ZipOutputStream(response.outputStream);
            def file1Entry = new ZipEntry('first_file.txt');
            zip.putNextEntry(file1Entry);
            zip.write("This is the content of the first file".bytes);
            def file2Entry = new ZipEntry('second_file.txt');
            zip.putNextEntry(file2Entry);
            zip.write("This is the content of the second file".bytes);
            zip.close();
        }
    }

Upvotes: 0

Durga
Durga

Reputation: 161

URL url2download = new URL(url)
File file = new File(filename)
file.bytes = url2download.bytes

Upvotes: 1

plotnik
plotnik

Reputation: 432

You can do it with HttpBuilder-NG:

// https://http-builder-ng.github.io/http-builder-ng/
@Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.3')

import groovyx.net.http.HttpBuilder
import groovyx.net.http.optional.Download

def target = 'https://gist.github.com/daicham/5ac8461b8b49385244aa0977638c3420/archive/17a929502e6dda24d0ecfd5bb816c78a2bd5a088.zip'

File file = HttpBuilder.configure {
    request.uri = target
}.get {
    Download.toFile(delegate, new File('a.zip'))
}

Upvotes: 0

Related Questions