I want to create SSE connection using Apache HTTPClient on client side. I have server which is sending text/event-stream data to client. I want to write client in java which would use apache HTTPClient to open SSE connection and listen the data received from server.
Following is my tried code attempt to do this but only one response is received but server is sending response on every 2 seconds.
new Thread(new Runnable() {
@Override public void run() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://localhost:9000/sse");
httpget.addHeader("Accept", "text/event-stream");
System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
System.out.println("Hey..." + entity);
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
httpclient.execute(httpget, responseHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Below are response headers sent by Server
"Content-Type: text/event-stream"
"Cache-Control: no-cache"
"Connection: keep-alive"
"Transfer-Encoding: chunked"
Is there way to listen live SSE stream using Apache HttpClient?