0
votes

When i hit an API through postman i am able to download a pdf file. When i hit the same API through java code i get pdf content in ResponseBody. And i am able to create a new pdf file with the responsebody content but when i open the file it is blank.

my question is how can i create a new file with the same content as in response.

i tried the foll. code to convert the response

file  = new File("/home/abc.pdf");
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            if (!file.exists()) {
                file.createNewFile();
            }

            byte[] contentInBytes = response.getBody().getBytes();
            System.out.println(Arrays.toString(contentInBytes));

            outputStream.write(contentInBytes);
            outputStream.flush();
            outputStream.close();
1

1 Answers

0
votes

Creating a temporary byte[] array to store the entire response body before saving it to a file is wasteful. You want to write the response InputStream to the OutputStream of your file.

This can be done in few ways, one will be to use Guava's ByteStreams.copy() e.g.:

try (OutputStream out = Files.newOutputStream(Paths.get("abc.pdf")) {
    ByteStreams.copy(response.getBody(), out);
}