一般用什么做网站首页,苏州市住房和城乡建设局网站,wordpress 文章顶踩插件,廊坊网页搜索排名提升SSE 调用
SSE#xff08;Sever-Sent Event#xff09;#xff0c;就是浏览器向服务器发送一个HTTP请求#xff0c;保持长连接#xff0c;服务器不断单向地向浏览器推送“信息”#xff08;message#xff09;#xff0c;这么做是为了节约网络资源#xff0c;不用一直…SSE 调用
SSESever-Sent Event就是浏览器向服务器发送一个HTTP请求保持长连接服务器不断单向地向浏览器推送“信息”message这么做是为了节约网络资源不用一直发请求建立新连接。
// 创建请求对象Request request new Request.Builder().url(String.format(sseApi, seeId))
// .post(requestBody) // 请求体
// .addHeader(Authorization, Bearer token).addHeader(Accept, text/event-stream)
// .addHeader(Content-Type, text/event-stream;charsetUTF-8).addHeader(Connection, keep-alive).build();OkHttpClient okHttpClient new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS) // 建立连接的超时时间.readTimeout(30, TimeUnit.SECONDS) // 建立连接后读取数据的超时时间.build();// 创建一个 CountDownLatch 对象其初始计数为1表示需要等待一个事件发生后才能继续执行。CountDownLatch eventLatch new CountDownLatch(1);// 实例化EventSource注册EventSource监听器 -- 创建一个用于处理服务器发送事件的实例并定义处理事件的回调逻辑final String[] finalMessage {};RealEventSource realEventSource new RealEventSource(request, new EventSourceListener() {Overridepublic void onEvent(EventSource eventSource, String id, String type, String data) {if (finish.equals(type)) { // 消息类型add 增量finish 结束error 错误interrupted 中断eventLatch.countDown();finalMessage[0] data;
// log.info(data); // 请求到的数据}}Overridepublic void onFailure(EventSource eventSource, Throwable t, Response response) {t.printStackTrace();}});// 与服务器建立连接realEventSource.connect(okHttpClient);// await() 方法被调用来阻塞当前线程直到 CountDownLatch 的计数变为0。eventLatch.await();return finalMessage[0];
异步调用
根据文档描述首先得通过异步 POST 请求获得 task_id 再根据 task_id 发送 GET 请求获得最终结果
// TODO 设置请求参数同 SSE 调用// 开启 Http 客户端
OkHttpClient okHttpClient new OkHttpClient();// 创建请求体
MediaType json MediaType.parse(application/json; charsetutf-8);
RequestBody requestBody RequestBody.create(json, requestParam.toString());// 第一步发送异步请求(POST)获取 task_id并存放到 taskIdFuture 中
CompletableFutureString taskIdFuture new CompletableFuture();Request requestForTaskId new Request.Builder().url(https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_turbo/async-invoke).post(requestBody).addHeader(Authorization, Bearer token).build();// 创建一个新的异步 HTTP 请求并指定请求的回调函数
okHttpClient.newCall(requestForTaskId).enqueue(new Callback() {// 在请求成功并返回响应时被调用Overridepublic void onResponse(Call call, Response response) throws IOException {if (response.isSuccessful()) {String responseBody response.body().string();System.out.println(requestForTaskId: responseBody);// 解析 JSON 响应获取 task_idJSONObject jsonObject JSON.parseObject(responseBody);String taskId jsonObject.getJSONObject(data).getString(task_id);// 将结果设置到 CompletableFuturetaskIdFuture.complete(taskId);} else {taskIdFuture.completeExceptionally(new Exception(Request for task_id failed));}}// 在请求失败时被调用Overridepublic void onFailure(Call call, IOException e) {taskIdFuture.completeExceptionally(e);}
});// 阻塞主线程等待 CompletableFuture 的结果设置了最大等待时间
String taskId taskIdFuture.get(10, TimeUnit.SECONDS);
System.out.println(Task ID: taskId);// TODO 第二步使用 task_id 发送同步请求(GET)获取最终响应结果和第四节基本一样同步调用
// TODO 设置请求参数同 SSE 调用// 开启 Http 客户端
OkHttpClient client new OkHttpClient();// 创建请求体
MediaType json MediaType.parse(application/json; charsetutf-8);
RequestBody requestBody RequestBody.create(json, requestParam.toString());// 创建请求对象
Request request new Request.Builder().url(https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_turbo/invoke).post(requestBody) .addHeader(Authorization, Bearer token).build();// 发送请求
Response response client.newCall(request).execute();// 处理响应
if (response.isSuccessful()) {String responseBody response.body().string();System.out.println(Response: responseBody);
} else {System.out.println(Request failed: response.code() response.message());
}