java - Jersey 异步下载 zip 文件

标签 java asynchronous jersey jax-rs

我目前使用的是 Jersey 2.13。我希望客户端从服务器下载一个zip文件,并且我希望服务器在下载完成后删除该文件。因此,我尝试了 AsyncResponse,这样我就可以注册一个 CompletionCallback 以便知道下载已完成。对于我当前的代码,客户端得到:“失败:HTTP 错误代码:415”。

服务器代码是:

@GET
@Path("/{id}")
@Produces({"application/zip"})
public void getResourceTree(@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id) throws IOException{
    asyncResponse.register(new CompletionCallback() {
        @Override
        public void onComplete(Throwable throwable) {

            if (throwable == null) {
                // no throwable - the processing ended successfully
                // (response already written to the client)
                // Delete temporary zip file...
            } else {
                throw new UnexpectedException("The user did not receive the zip file in path:"+ getResourceTreeZipName(id) +" successfully");
            }
        }
    });

    new Thread(new Runnable() {
        @Override
        public void run() {
                File file = createZipFile(id);
                asyncResponse.resume(Response.ok((Object) file).build());
        }
    }).start();
}

客户端代码是:

private File downloadZipFile(String resourceId){
    Client client = Client.create();
    WebResource serverWebResource = client.resource(serverURI+"/"+resourceId);
    ClientResponse response = serverWebResource.accept("application/zip").get(ClientResponse.class);
    InputStream in = response.getEntityInputStream();
    //Create and return the zip file from the input stream...
}

我做错了什么?

最佳答案

您是否尝试过使用其他 REST 工具(例如 Postman),并检查服务器在通过带有接受 header 的 GET 调用时是否返回正确的对象?我要做的第二件事是调试客户端并检查对象创建后是否设置了 header 接受。

关于java - Jersey 异步下载 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26732194/

相关文章:

jersey - 有没有办法将 JAX-RS 资源链接到 Spring HATEOAS 中的另一个资源?

java - 如何使用 Java 流查找数组列总和

java - 我试图通过迭代用整数填充数组,但出现 ArrayIndexOutOfBoundsException

python - 为什么我不应该使用异步(事件)IO

c++ - 如何将结构元素传递给异步线程?

使用 Jersey 的 Java Async REST Web 服务?

java - 以编程方式在android中动态创建 View 对象

java - 引发 "sun.misc.Unsafe.park"的线程异常并停止处理请求

javascript - 为什么这个 `Promise.all()` 语句不等待 promise 解决?

java - GuiceConfig 和 JSP_TEMPLATES_BASE_PATH