使用 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() {
            @Override
            public 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);   // 请求到的数据
                }
            }
            @Override
            public 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() {
    // 在请求成功并返回响应时被调用
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            System.out.println("requestForTaskId: " + responseBody);
            // 解析 JSON 响应获取 task_id
            JSONObject jsonObject = JSON.parseObject(responseBody);
            String taskId = jsonObject.getJSONObject("data").getString("task_id");
            // 将结果设置到 CompletableFuture
            taskIdFuture.complete(taskId);
        } else {
            taskIdFuture.completeExceptionally(new Exception("Request for task_id failed"));
        }
    }
 
    // 在请求失败时被调用
    @Override
    public 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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值