温馨提示×

Java怎么调用chatGPT接口

小亿
225
2023-12-01 09:09:51
栏目: 编程语言

要调用ChatGPT接口,你可以使用Java中的HTTP请求来发送POST请求,并将ChatGPT的API端点作为目标URL。以下是一个简单的Java代码示例,用于调用ChatGPT接口:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ChatGPTClient {

    public static void main(String[] args) {

        String apiEndpoint = “https://api.openai.com/v1/chat/completions”;

        String apiKey = “YOUR_API_KEY”; // 请替换为你的API密钥

        try {

            URL url = new URL(apiEndpoint);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            

            // 设置请求头

            conn.setRequestMethod(“POST”);

            conn.setRequestProperty(“Authorization”, "Bearer " + apiKey);

            conn.setRequestProperty(“Content-Type”, “application/json”);

            // 设置请求体

            String data = “{"prompt": "What is the weather like today?", "max_tokens": 50}”;

            

            conn.setDoOutput(true);

            OutputStream outputStream = conn.getOutputStream();

            outputStream.write(data.getBytes());

            outputStream.flush();

            

            // 发送请求并获取响应

            int responseCode = conn.getResponseCode();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()

            ));

            String line;

            StringBuilder response = new StringBuilder();

            while ((line = reader.readLine()) != null) {

                response.append(line);

            }

            reader.close();

            

            // 处理响应

            if (responseCode == 200) {

                System.out.println(“成功调用ChatGPT接口”);

                System.out.println(“响应结果:” + response.toString());

                // 在这里对响应进行进一步处理

            } else {

                System.out.println(“调用ChatGPT接口失败,HTTP状态码:” + responseCode);

                // 在这里处理错误情况

            }

            

            conn.disconnect();

        } catch (IOException e) {

            e.printStackTrace();

        }

    } }

在上面的代码示例中,你需要将apiEndpoint变量设置为ChatGPT的API端点URL,将apiKey变量设置为你的OpenAI API密钥。然后,你可以根据需要设置请求体中的promptmax_tokens字段。发送请求后,你可以通过conn.getResponseCode()方法获取HTTP状态码,通过conn.getInputStream()方法获取响应数据。请根据实际的业务逻辑对响应进行进一步处理。

0