Search code examples
javaspringrestresttemplate

Read attached PDF file using spring


I have a Get API by which can download PDF. Using Spring rest template I am able to get content but when I am creating PDF file it's creating a blank pdf.

I am using byte[] to create a new file.

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_PDF));
HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<String> result =
restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);


String content = response.getBody();
byte[] bytes = content.getBytes();
Files.write(Paths.get("/home/123.pdf"), bytes, StandardOpenOption.CREATE );

Please suggest me anyway to do it, Finally my objective
to upload in S3.


Solution

  • Your request headers should also include MediaType.APPLICATION_OCTET_STREAM

    This response object will return a byte array- which will be your pdf.

    So, the complete example would be something like this-

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_PDF, MediaType.APPLICATION_OCTET_STREAM));
    HttpEntity<String> entity = new HttpEntity<>(headers);
    
    ResponseEntity<byte[]> result =
    restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class);
    
    
    byte[] content = result.getBody();
    Files.write(Paths.get("/home/123.pdf"), content, StandardOpenOption.CREATE );
    

    Hope this helps.