使用Spring MVC的ResponseEntity返回流
我有一个Spring MVC方法,返回一个ResponseEntity
。根据检索到的特定数据,有时需要将数据流返回给用户。在其他时候,它会返回流以外的内容,有时还会返回重定向。我绝对希望它是一个流而不是字节数组,因为它可能很大。
当前,我使用以下代码片段返回流:
HttpHeaders httpHeaders = createHttpHeaders();IOUtils.copy(inputStream, httpServletResponse.getOutputStream());
return new ResponseEntity(httpHeaders, HttpStatus.OK);
不幸的是,这不允许Spring HttpHeaders
数据实际填充响应中的HTTP标头。这是有道理的,因为我的代码OutputStream
在Spring接收之前写入了ResponseEntity
。
以某种方式让Spring ResponseEntity
用InputStreama
让它处理它会很好。它还将与我的函数的其他路径平行,使我可以成功返回a ResponseEntity
。无论如何,我可以用Spring完成吗?
另外,我确实尝试将InputStream
in 返回,ResponseEntity
只是看看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有一些建议。
以上是 使用Spring MVC的ResponseEntity返回流 的全部内容, 来源链接: utcz.com/qa/435676.html