2014-10-01 60 views
0

我想實現讀取zip文件的rest服務。客戶調用此服務,並從響應中生成zip文件。我有這個爲我的服務:Rest服務讀取客戶端中的zip文件

@Produces({ "application/zip" }) 
@GET 
@Path("/fetchZip") 
public Response getZip() { 
try { 
    InputStream theFile = new FileInputStream("test.zip"); 
    ZipInputStream zis = new ZipInputStream(theFile); 
    return Response.ok(zis).build(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
return null; 
} 

任何人都可以讓我知道,如果這是正確的方式做到這一點?

+0

請問這種方法的工作?可能你必須指出你正在返回的內容類型。 – Victor 2014-10-01 16:00:15

+0

我試着添加內容類型,但這似乎不起作用 – Bharat 2014-10-01 19:10:59

+0

你可以發佈你正在做的請求和你得到的錯誤嗎? – Victor 2014-10-01 19:14:31

回答

0

嘗試這樣的事情,從響應的InputStream進行讀取和寫入FileOutputstream的文件:

 URL url = new URL("YOUR_URL"); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setDoOutput(true); 
    conn.setRequestMethod("GET"); 
    conn.setRequestProperty("Content-Type", "application/json"); 
    if (conn.getResponseCode() == 200) { 
     InputStream inputStream = conn.getInputStream(); 
     OutputStream output = new FileOutputStream("C:/yourFile.zip"); 
     byte[] buffer = new byte[1024]; 
     int bytesRead; 
     while ((bytesRead = inputStream.read(buffer)) != -1) { 
      output.write(buffer, 0, bytesRead); 
     } 
     output.close(); 
    } 
    conn.disconnect(); 
+0

我也試過,但是當我試圖打開zip文件時,它說它已損壞 – Bharat 2014-10-01 20:15:40