adam bien's blog

Receiving Server Sent Events (SSEs) with Plain Java SE 📎

Receiving Server Sent Events (SSE) with plain Java 11+:

The stream of string lines is "reactive", you will receive the events "on the go":


import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;

import org.junit.jupiter.api.Test;

public class HttpClientSSETest {

    @Test
    public void receiveEvents() throws URISyntaxException, IOException, InterruptedException {
        var uri = new URI("http://localhost:8080/sse");
        var client = HttpClient.newHttpClient();
        var request = HttpRequest.newBuilder(uri).GET().build();
        var lines = client.send(request, BodyHandlers.ofLines()).body();
        lines.forEach(System.out::println);
    }
}    

The project was created with the "hopefully shortest Java 16 starter". and the SSEs were sent with "mocking backend for frontends" aka mockend.