请以stream: true和长连接 的方式写一个方法,能直接被外部传参进行访问的实现。
时间: 2024-04-18 15:26:18 浏览: 108
基于流模式长连接的简单实现
5星 · 资源好评率100%
以下是一个使用 stream: true 和长连接方式的方法示例,可以通过传递参数进行访问:
```java
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 + ", \"stream\": true}";
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();
}
}
```
您可以将此代码放在一个类中,并通过传递参数调用 `sendRequest` 方法来访问 OpenAI API。请记得将 `YOUR_API_KEY` 替换为您自己的 API 密钥,并根据需要修改其他参数。
阅读全文