我正在寻找一种方法从rest模板获取打开的输入流 - 我试图使用ResponseExtractor,但是在返回之前流正在关闭,如下所示:
https://jira.spring.io/browse/SPR-7357
“请注意,您不能简单地从提取器中返回InputStream,因为到execute方法返回时,基础连接和流已经关闭”
我希望有一种方法,我不需要在其他模板中直接写入输出流。
I am looking for a way to get opened input stream from rest template - I was trying to used ResponseExtractor, but the stream is getting closed before returning, as written here:
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"
I hope that there is a way and I will not have to write to my output stream directly in the rest template.
最满意答案
我没有找到办法做到这一点,该流正在关闭。 作为解决方法,我创建了以下代码:
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; }它就像一个魅力! :)
I didn't find a way to do it, the stream is always getting closed. As a workaround I created the following code:
public interface ResourceReader { void read(InputStream content); }with the following implementation:
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); } } }then in controller:
@RequestMapping(value = "document/{objectId}") public void getDocumentContent(@PathVariable String objectId, HttpServletResponse response) { ResourceReader reader = new StreamResourceReader(response); service.readDocumentContent(objectId, reader); }call to rest template:
restTemplate.execute(uri, HttpMethod.GET, null, new StreamResponseExtractor(reader));and the string response extractor:
@Override public ResponseEntity extractData(ClientHttpResponse response) throws IOException { reader.read(response.getBody()); return null; }and it works like a charm! :)
更多推荐
发布评论