JavaでChatGPT APIを呼び出すには

Java で HTTP リクエストを使用して POST リクエストを送信し、ChatGPT の API エンドポイントをターゲット URL として指定することで、ChatGPT API を呼び出すことができます。以下に、ChatGPT API を呼び出すための簡単な Java コード例を示します。

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キーに設定する必要があります。 そして必要なリクエストボディーのpromptとmax_tokensフィールドを設定することができます。 リクエストを送信するとconn.getResponseCode()メソッドからHTTPステータスコードを取得でき、conn.getInputStream()メソッドからレスポンスデータを取得できます。 実際のビジネスロジックに従って、そのレスポンスをさらに処理してください。

bannerAds