Dav*_*d V 44 java spring servlets spring-mvc
我有一个Spring MVC方法返回一个ResponseEntity.根据检索到的特定数据,有时需要将数据流返回给用户.其他时候它会返回除流之外的其他内容,有时还会返回重定向.我绝对希望这是一个流而不是字节数组,因为它可能很大.
目前,我使用以下代码段返回流:
HttpHeaders httpHeaders = createHttpHeaders();
IOUtils.copy(inputStream, httpServletResponse.getOutputStream());
return new ResponseEntity(httpHeaders, HttpStatus.OK);
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不允许Spring HttpHeaders数据实际填充响应中的HTTP标头.这是有道理的,因为我的代码写入OutputStreamSpring之前收到的ResponseEntity.
这将是非常好的以某种方式返回一个ResponseEntity带有InputStream一个让Spring处理.它也会与我的函数的其他路径并行,我可以成功返回一个ResponseEntity.无论如何,我可以用Spring完成这个任务吗?
此外,我也尝试返回InputStream的ResponseEntity只是为了看看春天会接受它.
return new ResponseEntity(inputStream, httpHeaders, HttpStatus.OK);
Run Code Online (Sandbox Code Playgroud)
但它抛出了这个异常:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
Run Code Online (Sandbox Code Playgroud)
我可以通过HttpServletResponse直接设置所有内容来使我的功能工作,但我想只用Spring做到这一点.
Dav*_*d V 95
Spring的InputStreamResource效果很好.您需要手动设置Content-Length,否则Spring会尝试读取流以获取Content-Length.
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
httpHeaders.setContentLength(contentLengthOfStream);
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
Run Code Online (Sandbox Code Playgroud)
我从未发现任何建议使用此课程的网页.我只是猜到了,因为我注意到有一些使用ByteArrayResource的建议.
| 归档时间: |
|
| 查看次数: |
54320 次 |
| 最近记录: |