java调用chatgptapi接口
时间: 2023-09-27 22:04:05 浏览: 102
您好!要在Java中调用ChatGPT API接口,您可以使用Java的HTTP库(如OkHttp或Apache HttpClient)来发送HTTP请求并处理响应。下面是一个简单的示例代码:
```java
import okhttp3.*;
public class ChatGPTAPI {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"message\":\"你好\"}");
Request request = new Request.Builder()
.url("https://api.chatgpt.com/v1/messages")
.post(body)
.addHeader("Authorization", "Bearer YOUR_API_KEY")
.addHeader("Content-Type", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
} else {
System.out.println("Request failed with code: " + response.code());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上述代码中,您需要替换`YOUR_API_KEY`为您的ChatGPT API密钥。然后,您可以调用`client.newCall(request).execute()`来发送请求并获取响应。请注意,此示例仅适用于与ChatGPT API交互的简单对话。
希望这可以帮助到您!如果您有任何其他问题,请随时提问。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)