使用Groovy下载zip文件

时间:2018-04-11 11:41:47

标签: groovy zipfile

我需要使用groovy从网址下载zip文件。

测试网址:https://gist.github.com/daicham/5ac8461b8b49385244aa0977638c3420/archive/17a929502e6dda24d0ecfd5bb816c78a2bd5a088.zip

到目前为止我做了什么:

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

但是在打开下载的zip文件时,我收到错误“加载存档时出错”。

感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

你可以用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'))
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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();
        }
    }
相关问题