【发布时间】:2017-01-25 15:54:57
【问题描述】:
我正在尝试使用 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 所述)。
非常感谢任何提示。
【问题讨论】:
-
这里可能是相同的解决方案stackoverflow.com/questions/15781885/…
-
@Redlab 这是一个
FileSystemResource- 这会起作用 - 我的问题是InputStream在GET请求完成后关闭。所以我不能再往下用了。
标签: java spring spring-mvc