RestTemplate provides ways to download the file from another web service. exchange a method used to read binary data, Which will take

  • First argument – URL which returns file,
  • Second argument – Method Type,
  • Third argument – Entry object which contains Request Header information,
  • Fourth argument – Byte array.

The response will be ResponseEntity of bytes those can be written to a new file in a directory. Here is an example of Spring boot RestTemplate download file example:

Spring boot RestTemplate download file example code

   @Autowired
   private RestTemplateBuilder restTemplate;
   
   public void downloadFile(){     // This method will download file using RestTemplate
       try {
           HttpHeaders headers = new HttpHeaders();
           headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
           HttpEntity<String> entity = new HttpEntity<>(headers);
           ResponseEntity<byte[]> response = restTemplate.build()
                                                         .exchange("http://localhost:8080/downloadFile", HttpMethod.GET, entity, byte[].class);
           Files.write(Paths.get("e:\\download-files\\demo1.pdf"), response.getBody());
       }catch (Exception e){
           e.printStackTrace();
       }
   }

Output:

 

Spring boot RestTemplate Download File Example

Spring boot RestTemplate Download File Example

References:

Spring boot rest client document

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *