Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

java - Return a stream with Spring MVC's ResponseEntity

I have a Spring MVC method which returns a ResponseEntity. Depending on the specific data retrieved, it sometimes needs to return a stream of data to the user. Other times it will return something other than a stream, and sometimes a redirect. I most definitely want this to be a stream and not a byte array since it can be large.

Currently, I return the stream using the following snippet of code:

HttpHeaders httpHeaders = createHttpHeaders();
IOUtils.copy(inputStream, httpServletResponse.getOutputStream());

return new ResponseEntity(httpHeaders, HttpStatus.OK);

Unfortunately, this does not allow the Spring HttpHeaders data to actually populate the HTTP Headers in the response. This makes sense since my code writes to the OutputStream before Spring receives the ResponseEntity.

It would be very nice to somehow return a ResponseEntity with an InputStream an let Spring handle it. It also would parallel the other paths of my function where I can successfully return a ResponseEntity. Is there anyway I can accomplish this with Spring?


Also, I did try returning the InputStream in the ResponseEntity just to see if Spring would accept it.

return new ResponseEntity(inputStream, httpHeaders, HttpStatus.OK);

But it throws this exception:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

I can get my function to work by setting everything on the HttpServletResponse directly, but I would like to do this only with Spring.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Spring's InputStreamResource works well. You need to set the Content-Length manually, or it appears that Spring attempts to read the stream to obtain the Content-Length.

InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
httpHeaders.setContentLength(contentLengthOfStream);
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);

I never found any web pages suggesting using this class. I only guessed it because I noticed there were a few suggestions for using ByteArrayResource.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...