Our team has developed Server-Sent events (SSE) for a specific task.
I am trying to build a client to listen to event streams from our server. I have sort of managed to do this using the Jersey libraries for Java. However since most of our client code uses Spring, I would like to have an example of how this could be done using Spring.
I was able to find many examples on SSE on the server side for Spring. However I am unable to find any documentation for the client side.
Does Spring support SSE on the client side? If yes, may I have an example of how the following can be achieved using Spring...
Send an HTTP GET request to our server...
GET -> http://example.com/api/events/
headers ->
Accept:text/event-stream
sessionKey:someString
The response will be a text stream, that the client will continue to receive, until the client chooses to close the connection.
Have a look at one of the execute methods of the Spring RestTemplate. They all take a ResponseExtractor as parameter. This callback interface defines one method: extractData(ClientHttpResponse response). By providing your own ResponseExtractor you can do what you want with the response, like reading from it line-by-line. Naive example:
restTemplate.execute(a_url, HttpMethod.GET, request -> {
}, response -> {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody()));
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
System.out.println("Got some data, let's use my ObjectMapper to parse into something useful!");
}
} catch (IOException e) {
//Something clever
}
return response;
});