Get open input stream from rest template for big file processing

I'm looking for a way to get an open input stream from a rest template - I tried to use a ResponseExtractor, but the stream closes before returning, as written here:

https://jira.spring.io/browse/SPR-7357

"Note that you cannot just return an InputStream from the extractor, because by the time the execution method returns, the base connection and stream are already closed."

I hope there is a way, and I do not have to write to the output stream directly in the remainder template.

+5
source share
1 answer

I did not find a way to do this, the thread always closes. 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 the controller:

 @RequestMapping(value = "document/{objectId}") public void getDocumentContent(@PathVariable String objectId, HttpServletResponse response) { ResourceReader reader = new StreamResourceReader(response); service.readDocumentContent(objectId, reader); } 

rest pattern call:

 restTemplate.execute(uri, HttpMethod.GET, null, new StreamResponseExtractor(reader)); 

and line response extractor:

 @Override public ResponseEntity extractData(ClientHttpResponse response) throws IOException { reader.read(response.getBody()); return null; } 

and it works like a charm! :)

+1
source

Source: https://habr.com/ru/post/1241180/


All Articles