写一个用java调用chatgptapi的代码
时间: 2023-05-17 10:07:35 浏览: 148
非常感谢您的提问,以下是一个使用Java调用ChatGPT API的示例代码:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
public class ChatGPTAPI {
public static void main(String[] args) throws IOException {
String url = "https://api.chatgpt.com/chat";
String apiKey = "YOUR_API_KEY";
String prompt = "Hello, how are you?";
String payload = "{\"prompt\": \"" + prompt + "\"}";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + apiKey);
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(payload);
wr.flush();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
```
请注意,您需要将 `YOUR_API_KEY` 替换为您自己的 ChatGPT API 密钥。此外,您还需要确保您的 Java 环境已正确配置,以便能够进行网络请求。
阅读全文