请写出现在Java 对接OpenAI api 的完整代码
时间: 2024-04-18 19:26:52 浏览: 170
Java 写的与OPEN AI 模型的 API 进行交互的源代码.zip
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class OpenAIJavaExample {
public static void main(String[] args) {
try {
String apiKey = "YOUR_API_KEY";
String prompt = "Hello, world!";
String model = "gpt-3.5-turbo";
int maxTokens = 10;
String response = OpenAIJavaExample.sendRequest(apiKey, prompt, model, maxTokens);
System.out.println("Response: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String sendRequest(String apiKey, String prompt, String model, int maxTokens) throws IOException {
String url = "https://api.openai.com/v1/engines/" + model + "/completions";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Set the request method and headers
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + apiKey);
// Build the JSON request body
String requestBody = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + "}";
con.setDoOutput(true);
try (OutputStream os = con.getOutputStream()) {
byte[] input = requestBody.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Send the request and get the response
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
阅读全文