在向https://api.openai.com/v1/completions发起Http请求之前,使用java.net包下面的Proxy进行代理。 代码如下: public class OpenAiApi { public Stri
在向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;}
来源地址:https://blog.csdn.net/dantui_/article/details/130072028
--结束END--
本文标题: 调用OpenAi出现连接超时的解决方案
本文链接: https://lsjlt.com/news/392005.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0