使用java生成调用openai接口的程序
时间: 2023-08-31 11:10:26 浏览: 295
以下是使用Java生成调用OpenAI接口的程序示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class OpenAI {
public static void main(String[] args) {
try {
// Replace with your API key
String apiKey = "YOUR_API_KEY";
// Replace with your prompt
String prompt = "In a shocking finding, scientists discovered a herd of unicorns living in a remote, previously unexplored valley, in the Andes Mountains. Even more surprising to the researchers was the fact that the unicorns spoke perfect English.";
// Encode the prompt
String encodedPrompt = URLEncoder.encode(prompt, "UTF-8");
// Create the URL for the API call
URL url = new URL("https://api.openai.com/v1/completions?prompt=" + encodedPrompt);
// Create the HTTP connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method and headers
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
// Read the response from the API
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder responseBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
reader.close();
// Print the response from the API
System.out.println(responseBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个程序使用Java中的`HttpURLConnection`类来创建HTTP连接并发送API请求。它需要一个OpenAI API密钥和一个提示来生成文本。程序将提示编码为URL编码格式,然后将其添加到API调用的URL中。它还设置了HTTP请求的请求方法和标头,并从API读取响应。最后,程序将API的响应打印到控制台上。
阅读全文