1

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();
} 
RRR_J
  • 345
  • 2
  • 6
  • 19
  • Have you tried bufferedoutputstream and flush it in finally, and add one more catch to get any exception type using Exception e – Niraj Jha Feb 04 '20 at 07:02
  • Finally found an issue, we didn't pass the correct authentication header due to which the response stream was not having anything! – RRR_J Feb 04 '20 at 07:57

0 Answers0