我有一个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做到这一点.