Java怎么调用chatGPT接口

48次阅读
没有评论

共计 2243 个字符,预计需要花费 6 分钟才能阅读完成。

要调用 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() 方法获取响应数据。请根据实际的业务逻辑对响应进行进一步处理。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-09发表,共计2243字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)