下载大文件

RestTemplategetForObjectgetForEntity 方法将整个响应加载到内存中。这不适合下载大文件,因为它可能导致内存不足异常。此示例显示如何流式传输 GET 请求的响应。

RestTemplate restTemplate // = ...;

// Optional Accept header
RequestCallback requestCallback = request -> request.getHeaders()
        .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));

// Streams the response instead of loading it all in memory
ResponseExtractor<Void> responseExtractor = response -> {
    // Here I write the response to a file but do what you like
    Path path = Paths.get("some/path");
    Files.copy(response.getBody(), path);
    return null;
};
restTemplate.execute(URI.create("www.something.com"), HttpMethod.GET, requestCallback, responseExtractor);

请注意,你不能简单地从提取器返回 InputStream,因为在 execute 方法返回时,底层连接和流已经关闭。