How to stream endless InputStream with JAX-RS

I have an infinite InputStream with some data that I want to return in response to an HTTP GET request. I want my web / API client to read it endlessly. How can I do this using JAX-RS? I try this:

 @GET @Path("/stream") @Produces(MediaType.TEXT_PLAIN) public StreamingOutput stream() { final InputStream input = // get it return new StreamingOutput() { @Override public void write(OutputStream out) throws IOException { while (true) { out.write(input.read()); out.flush(); } } }; } 

But the content is not displayed to the client. However, if I add OutputStream#close() , the server is delivering content at this very moment. How can I make it really affordable?

+6
source share
2 answers

So, you have flash issues, you can try to get ServletResponse, as the spec says:

The @Context annotation can be used to indicate a dependency on a Resource defined by servlets. The following servlet types MUST support servlet-based injection: ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse.

The introduced HttpServletResponse allows the resource method to complete an HTTP response before returning. An implementation MUST check for a fixed state and only process the return value if the response has not yet been completed.

Then we clear everything that you can, for example:

 @Context private HttpServletResponse context; @GET @Path("/stream") @Produces(MediaType.TEXT_PLAIN) public String stream() { final InputStream input = // get it ServletOutputStream out = context.getOutputStream(); while (true) { out.write(input.read()); out.flush(); context.flushBuffer(); } return ""; } 
+2
source

Just a wild guess:

 @GET @Path("/stream") @Produces(MediaType.TEXT_PLAIN) public Response stream() { final InputStream input = getit(); return Response.ok(input, MediaType.TEXT_PLAIN_TYPE).build(); } 
0
source

All Articles