I am using org.glassfish.jersey.server.ChunkedOutput to get the chunked response to my request. When I hit the URL through browser, instead of getting output as separate chunks, I am getting all the chunks at once. But when I use a Test Client to hit the resource, I get the output as separate chunks.
Server Used: Glassfish 4.0 Jersey version 2.13
Resource method is as follows:
@GET
@Path("chunk")
public ChunkedOutput<String> getChunkedResponse(@Context HttpServletRequest request) {
final ChunkedOutput<String> output = new ChunkedOutput<String>(
String.class);
new Thread() {
public void run() {
try {
Thread.sleep(2000);
String chunk;
String arr[] = { "America\r\n", "London\r\n", "Delhi\r\n", "null" };
int i = 0;
while (!(chunk = arr[i]).equals("null")) {
output.write(chunk);
i++;
Thread.sleep(2000);
}
} catch (IOException e) {
logger.error("IOException : ", e);
} catch (InterruptedException e) {
logger.error("InterruptedException : ", e);
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error("IOException IN finally : ", e);
}
}
}
}.start();
// the output will be probably returned even before
// a first chunk is written by the new thread
return output;
}
Test Client method is as follows:
private static void testChunkedResponse(WebTarget target){
final Response response = target.path("restRes").path("chunk")
.request().get();
final ChunkedInput<String> chunkedInput =
response.readEntity(new GenericType<ChunkedInput<String>>() {});
String chunk;
while ((chunk = chunkedInput.read()) != null) {
logger.info("Next chunk received: " + chunk);
}
}
Can someone please help me understand why response is not getting chunked on browser and what can be done about it?
I am also working on the client to process the chunkedouput response. From my knowledge,
I had the same problem. Adding line separator when writing solved the problem.
output.write(chunk + System.lineSeparator());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With