import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
public class SseExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://example.com/sse")
.build();
// 创建EventSource并设置监听器
EventSource eventSource = new EventSource.Factory(client).newEventSource(request, new EventSourceListener() {
@Override
public void onEvent(EventSource eventSource, String id, String type, String data) {
System.out.println("Event received:");
System.out.println("Id: " + id);
System.out.println("Type: " + type);
System.out.println("Data: " + data);
}
@Override
public void onFailure(EventSource eventSource, Throwable throwable, Response response) {
if (response != null) {
System.out.println("EventStream failed: " + response);
} else {
throwable.printStackTrace();
}
}
@Override
public void onClosed(EventSource eventSource, Integer code, String reason) {
System.out.println("EventStream closed. Code: " + code + " Reason: " + reason);
}
});
// 运行EventSource
eventSource.start();
}
}
这段代码演示了如何使用OkHttp库创建一个EventSource来处理服务端发送的服务器发送事件(SSE)。它定义了一个EventSourceListener,用于处理接收到的事件和连接失败。当main方法被调用时,它会创建一个EventSource,并开始接收服务端发送的事件。