Reputation: 121
I have a large file download that is served by a RestController on one server, that I need to stream through a RestController on another server. When calling the end server directly the result streams fine. However when using RestTemplate to call this server and then write the response to an OutputStream, the response is buffered on the front server until the whole file is ready, and then streamed. Is there a way I can write the file to an OutputStream as it comes in?
At the moment my code on the front server looks similar to this
@ResponseBody
public void downloadResults(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String jobId, OutputStream stream)
throws IOException
{
byte[] data = restTemplate.exchange("http://localhost/getFile", HttpMethod.POST, requestEntity, byte[].class, parameters).getBody();
stream.write(data);
}
I've set my RestTemplate to not buffer and I've verified that this is working by checking the Request type that is used, (SimpleStreamingClientHttpRequest). The data all comes back correct, its just only written to the stream all at once, rather than as it comes in
Upvotes: 8
Views: 12918
Reputation: 483
You can use restTemplate.execute. See https://www.baeldung.com/spring-resttemplate-download-large-file
Upvotes: 1
Reputation: 59221
RestTemplate
is not meant for streaming the response body, as pointed out in this JIRA issue.
Upvotes: 1