我正在尝试使用spring将文件下载的结果直接传输到另一个帖子 RestTemplate
我目前的做法如下:
ResponseEntitydownloadResponse = restTemplate.getForEntity(fileToDownloadUri, InputStreamResource.class); InputStreamResource imageInputStreamResource = downloadResponse.getBody(); ResponseEntity 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
关闭,流不再可处理.
我希望能够实现这个场景,而不必完全存放文件在内存中或将其写入文件(如描述在这里).
任何提示都非常感谢.
如果要直接转发响应而不将其保留在内存中,则必须直接写入响应:
@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; }); }