Java调用ChatGPT接口教程:快速入门指南
要调用ChatGPT接口,您需要使用Java中的HTTP客户端库,比如Apache HttpClient或OkHttp。以下是一个使用Apache HttpClient的示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class ChatGPTClient {
private static final String CHATGPT_API_URL = 'https://api.openai.com/v1/engines/davinci-codex/completions';
private final String apiKey;
public ChatGPTClient(String apiKey) {
this.apiKey = apiKey;
}
public String sendMessage(String message) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(CHATGPT_API_URL);
request.addHeader('Authorization', 'Bearer ' + apiKey);
request.addHeader('Content-Type', 'application/json');
String requestBody = {'prompt':'' + message + '','temperature':0.7,'max_tokens':60,'top_p':1,'frequency_penalty':0,'presence_penalty':0};
StringEntity params = new StringEntity(requestBody);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
} else {
throw new IOException('Empty response from chatbot server');
}
}
}
在上述代码中,您需要将CHATGPT_API_URL替换为ChatGPT API的URL,将apiKey替换为您的OpenAI API密钥。sendMessage方法接受一个字符串参数,表示要发送给ChatGPT的消息。该方法将返回一个字符串,表示ChatGPT的响应。
原文地址: https://www.cveoy.top/t/topic/naud 著作权归作者所有。请勿转载和采集!