

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:
Table of Contents
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
References:
Spring boot rest client document
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
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.