java 调用chatgpt api
时间: 2023-10-16 20:09:43 浏览: 164
ChatGPT Java API
对于Java调用chatgpt API的问题,可以使用以下代码示例:
```java
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class ChatGptApi {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static void main(String[] args) {
String apiUrl = "https://api.chatgpt.com/v1/messages";
String apiKey = "YOUR_API_KEY"; // 替换为你自己的API Key
OkHttpClient client = new OkHttpClient();
String prompt = "Hello, how are you?"; // 输入的聊天内容
String json = "{\"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}]}";
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(apiUrl)
.post(body)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
System.out.println(responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文