当前位置: 首页 > news >正文

使用 OKhttp3 实现 智普AI ChatGLM HTTP 调用(SSE、异步、同步)

SSE 调用

SSE(Sever-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;charset=UTF-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; charset=utf-8");
RequestBody requestBody = RequestBody.create(json, requestParam.toString());// 第一步:发送异步请求(POST)获取 task_id,并存放到 taskIdFuture 中
CompletableFuture<String> 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; charset=utf-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());
}
http://www.lryc.cn/news/365201.html

相关文章:

  • 智慧校园教学模式的崛起:优化学习体验
  • ffmpeg视频编码原理和实战-(5)对编码过程进行封装并解决丢帧问题
  • halo进阶-主题插件使用
  • 资深开发推荐的IDEA 插件
  • 数学题目系列(一)|丑数|各位和|埃氏筛|欧拉筛
  • k8s学习--Secret详细解释与应用
  • 功能问题:如何防止接口重复请求?
  • 系统架构设计师【第5章】: 软件工程基础知识 (核心总结)
  • 嵌入式Linux系统编程 — 2.2 标准I/O库:检查或复位状态
  • pESC-HIS是什么,怎么看?-实验操作系列-2
  • 树形表/树形数据接口的开发
  • 二叉树的镜像--c++【做题记录】
  • redis安裝启动
  • 为什么Java中的main方法必须是public static void的?
  • shell的编程方式
  • 前端面试项目细节重难点(已工作|做分享)想(八)
  • Loguru,一个 Python 日志神器
  • C++ 反转单词
  • Apache Doris 基础 -- 数据表设计(表索引)
  • 资源描述框架的用途及实际应用解析
  • 工业级物联网边缘网关解决方案-天拓四方
  • 认识微服务,认识Spring Cloud
  • 电脑设置密码怎么设置?让你的电脑更安全!
  • 搜维尔科技:SenseGlove Nova2使用主动接触反馈来模拟手掌的感觉,结合力反馈和振动触觉反馈,使其成为市场上第一款具有手掌反馈的无线触觉手套
  • 基于Python的实验室管理系统的设计与实现(论文+源码)_kaic
  • Windows系统WDS+MDT网络启动自动化安装
  • Apple开发者证书创建完整过程
  • for深入学习
  • 引用(C++)和内联函数
  • 【stm32/CubeMX、HAL库】swjtu嵌入式实验七 ADC 实验