我有一个返回 ResponseEntity
的 Spring MVC 方法。根据检索到的具体数据,它有时需要向用户返回数据流。有时它会返回流以外的东西,有时还会返回重定向。我绝对希望这是一个流而不是字节数组,因为它可能很大。
目前,我使用以下代码片段返回流:
HttpHeaders httpHeaders = createHttpHeaders();
IOUtils.copy(inputStream, httpServletResponse.getOutputStream());
return new ResponseEntity(httpHeaders, HttpStatus.OK);
不幸的是,这不允许 Spring HttpHeaders
数据实际填充响应中的 HTTP header 。这是有道理的,因为我的代码在 Spring 收到 ResponseEntity
之前写入 OutputStream
。
以某种方式返回带有 InputStream
的 ResponseEntity
并让 Spring 处理它会非常好。它还将与我可以成功返回 ResponseEntity
的函数的其他路径平行。无论如何我可以用 Spring 完成这个吗?
另外,我确实尝试在 ResponseEntity
中返回 InputStream
以查看 Spring 是否会接受它。
return new ResponseEntity(inputStream, httpHeaders, HttpStatus.OK);
但它会抛出这个异常:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
我可以通过直接在 HttpServletResponse
上设置所有内容来使我的函数工作,但我只想使用 Spring 来执行此操作。
最佳答案
Spring 的InputStreamResource效果很好。您需要手动设置 Content-Length,否则 Spring 似乎试图读取流以获取 Content-Length。
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
httpHeaders.setContentLength(contentLengthOfStream);
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
我从未找到任何建议使用此类的网页。我只是猜到了,因为我注意到有一些关于使用 ByteArrayResource 的建议。
关于java - 返回带有 Spring MVC 的 ResponseEntity 的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333394/