How can RestTemplate retrieve a file stream?

When using RestTemplate to retrieve a file stream, you can use ResponseEntity to get the file stream. Here is an example code:

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Resource> response = restTemplate.getForEntity("http://example.com/file.pdf", Resource.class);

try (InputStream inputStream = response.getBody().getInputStream()) {
    // 处理文件流
    // 例如保存文件到本地
    Files.copy(inputStream, Paths.get("file.pdf"));
} catch (IOException e) {
    e.printStackTrace();
}

In the example above, we used RestTemplate to send a GET request to fetch a file stream, and we retrieved the file stream through ResponseEntity. We then used the inputStream to handle the file stream, such as saving the file locally. It is important to remember to close the inputStream after handling the file stream to release resources.

bannerAds