使用java发送OpenAi API请求怎么写
时间: 2024-05-10 21:20:28 浏览: 270
以下是使用Java发送OpenAI API请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class OpenAIRequest {
public static void main(String[] args) {
String apiKey = "YOUR_API_KEY";
String prompt = "Hello, ";
String apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";
try {
URL url = new URL(apiUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bearer " + apiKey);
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
String input = "{\"prompt\": \"" + prompt + "\",\"max_tokens\": 5,\"temperature\": 0.7}";
byte[] inputBytes = input.getBytes("utf-8");
con.getOutputStream().write(inputBytes);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
这个示例代码使用了java.net.HttpURLConnection类来发送HTTP请求。首先,我们需要设置要连接的URL地址和API密钥。然后,我们创建一个HttpURLConnection对象,并设置请求方法、HTTP头、请求体等参数。最后,我们从响应流中读取响应并显示在控制台上。
请注意,这个示例代码只是一个简单的示例,并且不包含任何错误处理和异常情况的处理。在实际应用中,您应该根据需要进行适当的错误处理和异常情况的处理。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)