从 rest 模板获取打开的输入流以进行大文件处理
Get opened input stream from rest template for large file processing
我正在寻找一种从 rest 模板中获取打开的输入流的方法 - 我试图使用 ResponseExtractor,但是在返回之前流正在关闭,如下所示:
https://jira.spring.io/browse/SPR-7357
"Note that you cannot simply return the InputStream from the extractor, because by the time the execute method returns, the underlying connection and stream are already closed"
我希望有办法,我将不必直接在其余模板中写入我的输出流。
我没找到办法,流总是关闭。作为解决方法,我创建了以下代码:
public interface ResourceReader {
void read(InputStream content);
}
实施如下:
public class StreamResourceReader implements ResourceReader {
private HttpServletResponse response;
public StreamResourceReader(HttpServletResponse response) {
this.response = response;
}
@Override
public void read(InputStream content) {
try {
IOUtils.copy(content, response.getOutputStream());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
然后在控制器中:
@RequestMapping(value = "document/{objectId}")
public void getDocumentContent(@PathVariable String objectId, HttpServletResponse response) {
ResourceReader reader = new StreamResourceReader(response);
service.readDocumentContent(objectId, reader);
}
调用休息模板:
restTemplate.execute(uri, HttpMethod.GET, null,
new StreamResponseExtractor(reader));
和字符串响应提取器:
@Override
public ResponseEntity extractData(ClientHttpResponse response) throws IOException {
reader.read(response.getBody());
return null;
}
它就像一个魅力! :)
我正在寻找一种从 rest 模板中获取打开的输入流的方法 - 我试图使用 ResponseExtractor,但是在返回之前流正在关闭,如下所示:
https://jira.spring.io/browse/SPR-7357
"Note that you cannot simply return the InputStream from the extractor, because by the time the execute method returns, the underlying connection and stream are already closed"
我希望有办法,我将不必直接在其余模板中写入我的输出流。
我没找到办法,流总是关闭。作为解决方法,我创建了以下代码:
public interface ResourceReader {
void read(InputStream content);
}
实施如下:
public class StreamResourceReader implements ResourceReader {
private HttpServletResponse response;
public StreamResourceReader(HttpServletResponse response) {
this.response = response;
}
@Override
public void read(InputStream content) {
try {
IOUtils.copy(content, response.getOutputStream());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
然后在控制器中:
@RequestMapping(value = "document/{objectId}")
public void getDocumentContent(@PathVariable String objectId, HttpServletResponse response) {
ResourceReader reader = new StreamResourceReader(response);
service.readDocumentContent(objectId, reader);
}
调用休息模板:
restTemplate.execute(uri, HttpMethod.GET, null,
new StreamResponseExtractor(reader));
和字符串响应提取器:
@Override
public ResponseEntity extractData(ClientHttpResponse response) throws IOException {
reader.read(response.getBody());
return null;
}
它就像一个魅力! :)