我有一个 Jersey
服务将二进制数据输出为 StreamingOutput
、MediaType.APPLICATION_OCTET_STREAM
。
如何使用 Jersey
2 实现客户端来处理来自此类服务的响应
?
最佳答案
下面是一种实现 Jersey 2 客户端的方法,用于从 REST 服务下载文件,该服务返回二进制数据作为 StreamingOutput
和 MediaType.APPLICATION_OCTET_STREAM
-
Client client = ClientBuilder.newClient();
// change SERVER_URL, API_PATH and PATH as per REST API details
WebTarget webTarget = client.target(SERVER_URL).path(API_PATH).path(PATH);
Invocation.Builder invocationBuilder = webTarget.request();
Response response = invocationBuilder.get();
String contentDispositionHeader = response.getHeaderString("Content-Disposition");
String fileName = contentDispositionHeader
.substring(contentDispositionHeader.indexOf("filename=") + "filename=".length()).replace("\"", "");
InputStream responseStream = response.readEntity(InputStream.class);
// Set location here where you want to store downloaded file.
// It will replace the file if already exist in that location with same name.
Files.copy(responseStream, Paths.get("H:/"+ fileName), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File is downloaded");
关于java - StreamingOutput 的 Jersey 2 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22217660/