赞
踩
在向https://api.openai.com/v1/completions发起http请求之前,使用java.net包下面的Proxy进行代理。
代码如下:
- public class OpenAiApi {
-
-
- public String OpenAiAnswerer(CompletionRequest request, String openAiApiKey) {
-
- //代理
- String proxyHost = "代理地址";
- int proxyPort = 代理端口;
- String url = "https://api.openai.com/v1/completions";
- // json为请求体
- String json = JSONUtil.toJsonStr(request);
- String result = "";
- Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
- try {
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);
- connection.setRequestProperty("Authorization", "Bearer " + openAiApiKey);
- connection.setRequestProperty("Content-Type", "application/json");
-
- connection.setRequestMethod("POST");
-
- connection.setDoOutput(true);
- byte[] requestBodyBytes = json.getBytes(StandardCharsets.UTF_8);
- try (OutputStream outputStream = connection.getOutputStream()) {
- outputStream.write(requestBodyBytes, 0, requestBodyBytes.length);
- }
- try (InputStream inputStream = connection.getInputStream()) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
- StringBuilder response = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- response.append(line);
- }
- result = response.toString();
-
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- return JSONUtil.toBean(result, CompletionResponse.class);
- }
-
- }

connection.setRequestProperty("Authorization", "Bearer " + openAiApiKey);
connection.setRequestProperty("Content-Type", "application/json");
我在使用的时候忘记设置了Content-Type,结果一直报错,后面反复观看文档才发现这个必须得设置。
下面是OpenAiAnswerer方法里面形参类CompletionRequest,这里使用了Lombok插件里的@Data注解,自动填入get、set方法和无参构造。(如果添加了有参构造,那么务必加上无参构造)
- @Data
- public class CompletionRequest {
- private String model;
-
- private String prompt;
-
- private Integer max_tokens;
-
- private Integer temperature;
-
- private Integer top_p;
-
- private Integer n;
-
- private Boolean stream;
-
- private Integer logprobs;
-
- private String stop;
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。