如何使用Java / Spring Boot代码从服务器下载并保存Zip文件?

时间:2019-04-10 19:25:42

标签: java spring rest spring-boot zip

我需要开发一个API,该API可以打开与返回ZIP文件的URL的连接。从浏览器或Postman访问此URL时,它工作得很好,但是当我尝试从Java代码(尝试HttpClient / RestTemplate等)访问此URL时,它返回一个HTML文件。我想获取该zip文件并将其存储在特定目录中。

HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
                        HttpGet request = new HttpGet(url);
                        logger.info("Request to Asset Store: URL " + request.getURI());
                        HttpResponse response = client.execute(request);
                        if (response != null) {
                            for (Header header : response.getAllHeaders()) {
                                System.out.println(header.getName() + " - " + header.getValue());

                            }
                            BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
                            final ZipInputStream is = new ZipInputStream(bis);
                            try {
                                ZipEntry entry;
                                while ((entry = is.getNextEntry()) != null) {
                                    System.out.printf("File: %s Size %d Modified on %TD %n", entry.getName(),
                                            entry.getSize(), new Date(entry.getTime()));
                                    extractEntry(entry, is);
                                }
                                System.out.println("OUT");
                            } finally {
                                is.close();
                            }

                        }

private static void extractEntry(final ZipEntry entry, InputStream is) throws IOException {
        String exractedFile = "D://" + entry.getName();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(exractedFile);
            final byte[] buf = new byte[2048];
            int read = 0;
            int length;
            while ((length = is.read(buf, 0, buf.length)) >= 0) {
                fos.write(buf, 0, length);
            }
        } catch (IOException ioex) {
            fos.close();

0 个答案:

没有答案