从rest模板获取打开的输入流以进行大文件处理

zib*_*ibi 5 java rest spring spring-mvc resttemplate

我正在寻找一种从休息模板中获取打开的输入流的方法 - 我试图使用ResponseExtractor,但是在返回之前流已经关闭,如下所示:

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

"请注意,您不能简单地从提取器返回InputStream,因为在execute方法返回时,底层连接和流已经关闭"

我希望有一种方法,我不必直接在其余模板中写入我的输出流.

zib*_*ibi 2

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);
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

then in controller:

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

call to rest template:

restTemplate.execute(uri, HttpMethod.GET, null,
            new StreamResponseExtractor(reader));
Run Code Online (Sandbox Code Playgroud)

and the string response extractor:

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

and it works like a charm! :)