2

这个关于如何将二进制文件发送到客户端的问题相关。我正在这样做,实际上是我的方法@Produces("application/zip"),它适用于浏览器客户端。现在我正在尝试使用 Wink 客户端针对其余服务编写一些自动化测试。所以我的问题不是如何将文件发送到客户端,而是如何使用文件,作为 java rest 客户端(在本例中为 Apache Wink)。

我的资源方法如下所示... 一旦我有一个 Wink ClientResponse 对象,我如何从中获取文件以便我可以使用它?

  @GET
  @Path("/file")
  @Produces("application/zip")
  public javax.ws.rs.core.Response getFile() {

    filesToZip.put("file.txt", myText);

    ResponseBuilder responseBuilder = null;
    javax.ws.rs.core.Response response = null;
    InputStream in = null;
    try {

      in = new FileInputStream( createZipFile( filesToZip ) );
      responseBuilder = javax.ws.rs.core.Response.ok(in, MediaType.APPLICATION_OCTET_STREAM_TYPE);
      response = responseBuilder.header("content-disposition", "inline;filename="file.zip").build();

    } catch( FileNotFoundException fnfe) {
          fnfe.printStackTrace();
    }

    return response;

实际创建 zip 文件的方法如下所示

  private String createZipFile( Map<String,String> zipFiles ) {

    ZipOutputStream zos = null;
    File file = null;

    String createdFileCanonicalPath = null;

    try {

      // create a temp file -- the ZIP Container
      file = File.createTempFile("files", ".zip");
      zos = new ZipOutputStream( new FileOutputStream(file));

      // for each entry in the Map, create an inner zip entry

      for (Iterator<Map.Entry<String, String>> it = zipFiles.entrySet().iterator(); it.hasNext();){

        Map.Entry<String, String> entry = it.next();
        String innerFileName = entry.getKey();
        String textContent = entry.getValue();

        zos.putNextEntry( new ZipEntry(innerFileName) );
        StringBuilder sb = new StringBuilder();
        byte[] contentInBytes = sb.append(textContent).toString().getBytes();
        zos.write(contentInBytes, 0, contentInBytes.length);
        zos.closeEntry();        
      }

      zos.flush();
      zos.close();

      createdFileCanonicalPath = file.getCanonicalPath(); 

    } catch (SecurityException se) {
      se.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (zos != null) {
          zos.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return createdFileCanonicalPath;

  }
4

1 回答 1

1

您可以将其简单地用作输入流并用于ZipInputStream解压缩它。

这是使用 Apache HTTP 客户端的示例:

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    get.addHeader(new BasicHeader("Accept", "application/zip"));
    HttpResponse response = httpclient.execute(get);
    InputStream is = response.getEntity().getContent();
    ZipInputStream zip = new ZipInputStream(is);
于 2013-03-07T09:13:14.297 回答