I have been trying to consume one REST endpoint whose output is PDF file. The source endpoint returns the PDF correctly but when I use Spring weblclient to consume like below and convert to file, it gives error "file is corrupted" on opening.
Tried byte array resource as well (How to best get a byte array from a ClientResponse from Spring WebClient?) but I doubt the byte conversion might be causing the file to corrupt hence used InputStream but same issue, any pointers please?
Sample code
InputStream mono = WebClient.create().get().uri(UriComponentsBuilder.fromUriString(serviceUri)).build().toUri())
.accept(MediaType.APPLICATION_PDF)
.exchange()
.flatMap(response -> response.bodyToMono(InputStreamResource.class))
.map(inputStreamResource -> {
try {
return inputStreamResource.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}).block();
try(OutputStream outputStream = new FileOutputStream("c:\\report.pdf")) {
try {
IOUtils.copy(mono, outputStream);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e | IOException e) {
e.printStackTrace();
}