使用Java语言实现ChatGPT聊天机器人的示例代码

337 阅读1分钟

ChatGPT是一个基于GPT模型的聊天机器人API,可以通过HTTP请求与其进行交互。以下是使用Java语言实现ChatGPT聊天机器人的示例代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class ChatGPTDemo {
    public static void main(String[] args) {
        try {
            String apiKey = "YOUR_API_KEY"; // 在ChatGPT官网申请的API Key
            String message = "你好"; // 要发送的消息

            // 构建请求URL
            String urlStr = "https://api.chatgpt.com/gpt3?message=" + URLEncoder.encode(message, "UTF-8");

            // 创建HTTP连接
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "Bearer " + apiKey);

            // 发送请求并获取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String response = in.readLine();
            in.close();

            // 解析响应并输出回复消息
            String reply = response.substring(1, response.length() - 1); // 去掉响应中的引号
            System.out.println("ChatGPT: " + reply);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,我们首先需要替换其中的YOUR_API_KEY为在ChatGPT官网申请的API Key。然后,我们构建了一个HTTP GET请求,将要发送的消息作为URL参数传递给ChatGPT API,并在HTTP头部中添加了Authorization字段进行身份验证。最后,我们解析API返回的JSON数据,提取出回复消息并输出。