The steps to download a file stream using RestTemplate are as follows:
- Instantiate a RestTemplate object:
RestTemplate restTemplate = new RestTemplate();
- Use the exchange method of RestTemplate to send an HTTP GET request and retrieve a file stream.
ResponseEntity<byte[]> response = restTemplate.exchange(
"http://example.com/file.pdf",
HttpMethod.GET,
null,
byte[].class
);
- Retrieve the byte array from the response body and save it to a file.
byte[] fileData = response.getBody();
FileOutputStream fos = new FileOutputStream("file.pdf");
fos.write(fileData);
fos.close();
In this way, you can use RestTemplate to download a file stream and save it to a local file. It is important to note that the URL and file name in the above code need to be replaced according to the actual situation.