智谱ChatGML调用快速教程(java)

流程:注册------>看文档------>找到自己的api------>编写测试代码

首先你要有一个账号 去官网注册即可 智谱AI开放平台

注册以后会免费赠送api  接着你可以查看api调用文档说明 智谱AI开放平台 

文档中会详细说明请求各种信息以及参数

编写java代码测试是否能打通

导入包

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

测试 

@Test
    public void zhiPu(){
        String apiUrl = "https://open.bigmodel.cn/api/XXX"; // 官网中说明文档的URL
        String apiKey = "6.6"; // 你的API密钥
        String inputText = "你好"; // 你想要问答的内容

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setDoOutput(true);

            // 创建请求体
            String jsonInputString = "{\"model\": \"glm-4\", \"messages\": [{\"role\": \"user\", \"content\": \"" + inputText + "\"}]}";

            // 发送请求体
            try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) {
                os.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
                os.flush();
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String responseLine;
                    StringBuilder response = new StringBuilder();

                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }

                    System.out.println("Response: " + response.toString());
                }
            } else {
                System.out.println("Failed to call GLM-4 API");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

到这里算是完成了,更多实用细节可以查看官网。

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值