gpt4 book ai didi

java - JAX-RS - Wink - 使用 Wink 客户端读取文件的正确方法

转载 作者:行者123 更新时间:2023-11-30 11:35:15 27 4
gpt4 key购买 nike

this question相关这是关于如何将二进制文件发送给客户端的。我正在这样做,实际上是我的方法 @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;

}

最佳答案

您可以将它简单地用作输入流并使用 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);

关于java - JAX-RS - Wink - 使用 Wink 客户端读取文件的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15217023/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com