使用 JAX-RS 客户端从 REST 服务下载文件

Download file from REST service using JAX-RS client

我正在尝试使用 JAX-RS 从 REST 服务下载文件。 这是我的代码,它通过发送 GET 请求调用下载:

private Response invokeDownload(String authToken, String url) {
    // Creates the HTTP client object and makes the HTTP request to the specified URL
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);

    // Sets the header and makes a GET request
    return target.request().header("X-Tableau-Auth", authToken).get();
}

但是,我在将 Response 转换为实际的 File 对象时遇到了问题。所以我所做的是:

public File downloadWorkbook(String authToken, String siteId, String workbookId, String savePath)
        throws IOException {
    String url = Operation.DOWNLOAD_WORKBOOK.getUrl(siteId, workbookId);
    Response response = invokeDownload(authToken, url);

    String output = response.readEntity(String.class);
    String filename; 
// some code to retrieve the filename from the headers
    Path path = Files.write(Paths.get(savePath + "/" + filename), output.getBytes());
    File file = path.toFile();
    return file;
}

创建的文件无效,我调试了代码并注意到输出包含这样的字符串(大得多):

PK ͢�F���� �[ Superstore.twb�ysI�7����ߡ���d�m3��f���

看起来像二进制。显然代码有问题。

如何从 Response 对象中获取字符串形式的 HTTP 响应正文?



编辑: REST API 参考中关于 HTTP 响应的引述:

Response Body

One of the following, depending on the format of the workbook:

The workbook's content in .twb format (Content-Type: application/xml)
The workbook's content in .twbx format (Content-Type: application/octet-stream)

正如您自己注意到的那样,您在这里处理的是二进制数据。所以你不应该从你的回应中创建一个字符串。最好获取输入流并将其通过管道传输到您的文件。

Response response = invokeDownload(authToken, url);
InputStream in = response.readEntity(InputStream.class);
Path path = Paths.get(savePath, filename);
Files.copy(in, path);

1) 我假设您现在已经清楚 "binary file" 和 "text file" 之间的区别。而且你只能将后者捕获到 "string".

2) Sebastian 为您提供了捕获二进制文件的绝妙建议(+1,Sebastian!)。非常重要:在这种情况下,您应该始终 设置 MIME 类型 (Content-Type: xxx/yyy)。 Here 是另一个可能有用的 link。

3) 最后,在某些情况下,您可能 想要 将 "binary" 数据视为文本。这就是电子邮件附件与 SMTP(一种文本协议)一起工作的方式。在这些情况下,您想使用 Base64 Encoding. For example: JAX-RS | Download PDF from Base64 encoded data