0

I am using StreamingOutput to stream output from GET service. However, even if partial output is written to outputStream, it is not displayed on Browser/cURL output. Data is displayed only after entire output is written to stream. In below code I have added Thread.sleep to simulate the delay in producing the data.

How can we make sure the data is available to client as soon as it is written to stream?

import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.io.*;

@Path("/stream")
@Produces("text/plain")
public class StreamResource {

    @GET
    public Response streamExample(){
        StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream out) throws IOException, WebApplicationException {
                Writer writer = new BufferedWriter(new OutputStreamWriter(out));
                for (int i = 0; i < 60 ; i++){
                    writer.write(i + " ");
                    writer.flush();
                    try {
                        Thread.sleep(1000); // Just to simulate delay in producing data
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
               
            }
        };
        return Response.ok(stream).build();
    }

}
Abhi
  • 1
  • 5

0 Answers0