简体   繁体   English

如何从Java的响应中读取Zip文件?

[英]How to read Zip file from response in Java?

I am currently working on JAX-RS, where I'm trying to send and receive Zip files. 我目前正在使用JAX-RS,正在尝试发送和接收Zip文件。 Currently for sending the zip file in response, I'm able to achieve it using the below code (verified the zip downloading by entering the URL in the browser), but I'm not clear about writing the code logic to read the Zip file from response. 目前,为了发送zip文件作为响应,我可以使用以下代码来实现它(通过在浏览器中输入URL验证zip下载),但是我不清楚编写代码逻辑来读取Zip文件的方法从回应。

Please help me to achieve this functionality. 请帮助我实现此功能。

@GET
@Produces({"application/zip"})
@Path("getProduct")
public Response getProduct() {
    String METHODNAME = "getProduct";
     if (LoggingHelper.isEntryExitTraceEnabled(LOGGER)) {
            LOGGER.entering(CLASSNAME, METHODNAME);
     }
     File file;
     try {
         Properties prop = getProp();
         file = new File(prop.getProperty("ZipLocation")+prop.getProperty("ProductZip"));
         byte[] buffer = new byte[5120];
         FileOutputStream fos = new FileOutputStream(file);
         ZipOutputStream zos = new ZipOutputStream(fos);
         ZipEntry ze= new ZipEntry(prop.getProperty("ProductOutfile"));
         zos.putNextEntry(ze);
         FileInputStream in = new FileInputStream("C:\\Documents\\ProductExtract.xml");
         int len;
         while ((len = in.read(buffer)) > 0) {
             zos.write(buffer, 0, len);
         }
         in.close();
         zos.closeEntry();
         zos.close();
     } catch (FileNotFoundException ex) {
            LOGGER.logp(Level.SEVERE, CLASSNAME, METHODNAME, ex.getMessage(), ex);
            return Response.status(204).entity(ex.getMessage()).build();
     } catch (Exception ex) {
        LOGGER.logp(Level.SEVERE, CLASSNAME, METHODNAME, ex.getMessage(), ex);
        return Response.status(204).entity(ex.getMessage()).build();
     }
     return Response.ok(file, "application/zip").header("Content-Disposition", "attachment; filename=\""+file.getName()+"\"")
            .header("Content-Type", "application/zip").header("Set-Cookie", "fileDownload=true; path=/").build();
}

Kindly let me know how can I achieve reading the zip file from response of the above code. 请让我知道如何从上述代码的响应中读取zip文件。

Once you are using the JAX-RS Client API , your client code can be like: 一旦使用了JAX-RS客户端API ,您的客户端代码就可以像这样:

Client client = ClientBuilder.newClient();
InputStream is = client.target("http://localhost:8080")
                       .path("api").path("getProduct")
                       .request().accept("application/zip")
                       .get(InputStream.class);

ZipInputStream zis = new ZipInputStream(is);

Then read the content of the ZipInputStream . 然后读取ZipInputStream的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM