java 连接chatgpt
时间: 2023-08-28 14:22:49 浏览: 253
要在Java中连接到ChatGPT,您可以使用REST API来发送HTTP请求。以下是一个简单的Java示例,演示如何使用Java发送HTTP请求与ChatGPT通信:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ChatGptClient {
public static void main(String[] args) {
String apiUrl = "https://api.openai.com/v1/chat/completions";
String apiKey = "YOUR_API_KEY";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(apiUrl);
httpPost.setHeader("Authorization", "Bearer " + apiKey);
httpPost.setHeader("Content-Type", "application/json");
String payload = "{\"prompt\": \"Hello, how are you?\", \"max_tokens\": 50}";
StringEntity entity = new StringEntity(payload);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请确保将`apiUrl`替换为ChatGPT的API端点,并将`apiKey`替换为您的API密钥。在上述示例中,我们使用了Apache HttpClient库来发送HTTP请求并获取响应。您可以根据需要修改请求的内容,例如更改提示或最大令牌数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [java 连接chatgpt](https://blog.csdn.net/qq_34874784/article/details/131144558)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* [使用java对接chatgpt(含全部代码)](https://blog.csdn.net/weixin_46064585/article/details/131350323)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文