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?

3 comments. Leave new

Getting null pointer exception for restTemplate.build(). Please help.

Can you please send us code so we can get more idea about it.

I’m using RestTemplate to download file as InputStream, front end uses Struts2. looking good examples.

Leave a Reply

Your email address will not be published.