java请求chatGpt
时间: 2024-06-09 10:09:30 浏览: 118
要请求使用ChatGPT,您需要使用OpenAI的API密钥和适当的REST API请求。以下是使用Java进行ChatGPT请求的基本示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class ChatGPTRequest {
public static void main(String[] args) {
try {
String apiKey = "YOUR_API_KEY";
String prompt = "Hello, how are you?";
String url = "https://api.openai.com/v1/engines/davinci-codex/completions?prompt=" + URLEncoder.encode(prompt, "UTF-8") + "&max_tokens=150&n=1";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + apiKey);
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) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,您需要替换 `YOUR_API_KEY` 为您的OpenAI API密钥, `prompt` 变量设置为您想要发送给ChatGPT的消息。此代码将返回ChatGPT响应的JSON格式。您可以从响应中提取ChatGPT的回复。请注意,此示例代码仅适用于OpenAI的Davinci Codex引擎。如果您使用其他引擎,则需要更改URL。
阅读全文