调试之后发现返回 http 的头不对, application/json; charset=UTF-8, 手动更改为 text/event-stream, 不抛异常, 但是不能进入具体事件代码, 有人知道为什么么?
随便找的一份代码
@Slf4j
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SseTest {
@Test
public void test01() {
// OkHttp 客户端
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.build();
// 事件源工厂
EventSource.Factory factory = EventSources.createFactory(okHttpClient);
// 请求体
String requestBody = "{ \"contents\":[\n" +
" {\"role\": \"user\",\n" +
" \"parts\":[{\"text\": \"Write a story about a magic backpack.\"}]\n" +
" }\n" +
" ]\n" +
" }";
// 请求对象
Request request = new Request.Builder()
.url("http://wainao.api-v2.cloudos.com/google/v1beta/models/gemini-pro:streamGenerateContent?key=AIzaSyBGJbctKS06Zn")
.post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody))
.build();
// 自定义监听器
EventSourceListener eventSourceListener = new ConsoleEventSourceListener();
// 创建事件
EventSource eventSource = factory.newEventSource(request, eventSourceListener);
// 等待线程结束
CountDownLatch countDownLatch = new CountDownLatch(1);
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Slf4j
class ConsoleEventSourceListener extends EventSourceListener {
@Override
public void onOpen(EventSource eventSource, Response response) {
log.info("OpenAI 建立 sse 连接...");
}
@Override
public void onEvent(EventSource eventSource, String id, String type, String data) {
log.info("OpenAI 返回数据:{}", data);
if ("[DONE]".equals(data)) {
log.info("OpenAI 返回数据结束了");
return;
}
}
@Override
public void onClosed(EventSource eventSource) {
log.info("OpenAI 关闭 sse 连接...");
}
@SneakyThrows
@Override
public void onFailure(EventSource eventSource, Throwable t, Response response) {
if (Objects.isNull(response)) {
log.error("OpenAI sse 连接异常:{}", t);
eventSource.cancel();
return;
}
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
log.error("OpenAI sse 连接异常 data:{},异常:{}", body.string(), t);
} else {
log.error("OpenAI sse 连接异常 data:{},异常:{}", response, t);
}
eventSource.cancel();
}
}