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