要調用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密鑰。然后,你可以根據需要設置請求體中的prompt
和max_tokens
字段。發送請求后,你可以通過conn.getResponseCode()
方法獲取HTTP狀態碼,通過conn.getInputStream()
方法獲取響應數據。請根據實際的業務邏輯對響應進行進一步處理。