Download file from REST service using JAX-RS client

I am trying to load a file from a REST service using JAX-RS. This is my code that triggers the download by sending a GET request:

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();
}

      

However, I am having to face problems converting the response to the actual File object. So, I did the following:

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;
}

      

The file generated is not valid, I was debugging the code and noticed that the output contains a line like this (much more):

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

It looks like binary code. Obviously there is something wrong with the code.

How do I get the HTTP response body as a string from the Response object?



Edit: Quoting from REST API link about HTTP response:

Response body

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

.Twb workbook content (Content-Type: application / xml )
.twbx workbook content (Content-Type: application / octet-stream )

+3


source to share


2 answers


As you can see, you are dealing with binary data. Therefore, you should not create a string from your answer. Better to get the input stream and pipe it to your file.



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

      

+6


source


1) I am assuming that by this point you clearly understand the difference between "binary" and "text file". And you can only capture the latter in a "string".

2) Sebastian gave you great advice on writing a binary file (+1, Sebastian!). VERY IMPORTANT: you should always set the MIME ( Content-Type: xxx/yyy

) type in such cases. There is another link here that might be helpful.



3) Finally, there are cases where you might WANT to treat "binary" data as text. This is how email applications work with SMTP (text-based protocol). In these cases, you want to use Base64 Encoding . For example: JAX-RS | Download PDF from Base64 encoded data

+1


source







All Articles