以下是一个使用Java调用ChatGPT API的示例代码

分享 未结 0 529
社区小编
社区小编 管理员 2023年3月9日 23:47 发表

以下是一个使用Java调用ChatGPT API的示例代码:

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class ChatGPTAPI {

public static void main(String[] args) {
try {
String apiKey = "YOUR_API_KEY";
String message = "Hello, how are you?";
String url = "https://api.chatgpt.com/chatgpt?apiKey=" + apiKey + "&message=" + URLEncoder.encode(message, "UTF-8");

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

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());
} catch (Exception e) {
System.out.println(e);
}
}
}
```

在上面的代码中,我们首先定义了一个apiKey和message变量,分别代表ChatGPT API的API密钥和要发送的消息。然后,我们将这些变量添加到API的URL中,并使用Java的URL和HttpURLConnection类发送GET请求。最后,我们读取API的响应并将其打印到控制台上。

请注意,我们在将消息添加到URL中时,使用了Java的URLEncoder类对消息进行编码,以确保它不包含任何特殊字符。此外,我们还使用了Java的BufferedReader类来读取API的响应,以便我们可以将其存储在一个StringBuffer对象中。

收藏(0)  分享
相关标签: chatgpt
问题没解决?让chatGPT帮你作答 智能助手
0个回复
  • 消灭零回复