调用OpenAi出现连接超时的解决方案
短信预约 -IT技能 免费直播动态提醒
在向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
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341