我正在尝试使用 spring 的 RestTemplate
将文件下载的结果直接流式传输到另一篇文章中
我目前的做法如下:
ResponseEntity<InputStreamResource> downloadResponse = restTemplate.getForEntity(fileToDownloadUri, InputStreamResource.class);
InputStreamResource imageInputStreamResource = downloadResponse.getBody();
ResponseEntity<String> response = restTemplate.exchange(storageUri, POST, new HttpEntity<>(imageInputStreamResource), String.class);
但是,我在运行上面的代码时遇到以下异常:
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://host:port/path/some.jpg": stream is closed; nested exception is java.io.IOException: stream is closed
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:6
...
Caused by: java.io.IOException: stream is closed
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.ensureOpen(HttpURLConnection.java:3348)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3373)
似乎响应总是作为处理的最后一步关闭。通过响应,HttpURLConnection
关闭,并且流不再可处理。
我希望能够实现这种情况,而不必将文件完全保存在内存中或将其写入文件(如 here 所述)。
非常感谢任何提示。
最佳答案
如果你想直接转发响应而不是将它保存在内存中,你必须直接写入响应:
@RequestMapping(value = "/yourEndPoint")
public void processRequest(HttpServletResponse response) {
RestTemplate restTemplate = new RestTemplate();
response.setStatus(HttpStatus.OK.value());
restTemplate.execute(
fileToDownloadUri,
HttpMethod.GET,
(ClientHttpRequest requestCallback) -> {},
responseExtractor -> {
IOUtils.copy(responseExtractor.getBody(), response.getOutputStream());
return null;
});
}
关于java - Spring RestTemplate 将响应流式传输到另一个请求中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856005/