openai http请求413 Connect to api.openai.com:443

文章目录


我在使用openai官网api请求问答的时候,http请求出现了413错误,报错信息如下:
在这里插入图片描述
openai提供的api地址

代码:

public String doChatGPT(String question) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost("https://api.openai.com/v1/chat/completions");
        post.addHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Bearer " + openAiKey);
        String paramJson = "{\n" +
                "     \"model\": \"gpt-3.5-turbo\",\n" +
                "     \"messages\": [{\"role\": \"user\", \"content\": \""+question+"\"}],\n" +
                "     \"temperature\": 0.7\n" +
                "   }";

        StringEntity stringEntity = new StringEntity(paramJson, ContentType.create("text/json", "UTF-8"));
        post.setEntity(stringEntity);

        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String jsonStr = EntityUtils.toString(response.getEntity());
            logger.info("jsoon={}", jsonStr);
            AIAnswer aiAnswer = JSON.parseObject(jsonStr, AIAnswer.class);
            StringBuilder answers = new StringBuilder();
            List<Choices> choices = aiAnswer.getChoices();
            for (Choices choice : choices) {
                answers.append(choice.getMessage().getContent());
            }
            return answers.toString();
        } else {
            throw new RuntimeException("api.openai.com Err Code is " + response.getStatusLine().getStatusCode());
        }
    }

最终解决方案是使用了本地代理
我在自己电脑上招待代理服务器设置,然后打开之后看代理地址和端口号
在这里插入图片描述
在这里插入图片描述

然后修改代码如下(主要增加了代理功能):

public String doChatGPT(String question) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 新增代码:增加代理
        String proxyHost = "127.0.0.1";
        int proxyPort = 10809;
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(proxy)
                .build();

        HttpPost post = new HttpPost("https://api.openai.com/v1/chat/completions");
        post.addHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Bearer " + openAiKey);
        // 新增代码:将代理类放入配置中
        post.setConfig(requestConfig);
        String paramJson = "{\n" +
                "     \"model\": \"gpt-3.5-turbo\",\n" +
                "     \"messages\": [{\"role\": \"user\", \"content\": \""+question+"\"}],\n" +
                "     \"temperature\": 0.7\n" +
                "   }";

        StringEntity stringEntity = new StringEntity(paramJson, ContentType.create("text/json", "UTF-8"));
        post.setEntity(stringEntity);

        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String jsonStr = EntityUtils.toString(response.getEntity());
            logger.info("jsoon={}", jsonStr);
            AIAnswer aiAnswer = JSON.parseObject(jsonStr, AIAnswer.class);
            StringBuilder answers = new StringBuilder();
            List<Choices> choices = aiAnswer.getChoices();
            for (Choices choice : choices) {
                answers.append(choice.getMessage().getContent());
            }
            return answers.toString();
        } else {
            throw new RuntimeException("api.openai.com Err Code is " + response.getStatusLine().getStatusCode());
        }
    }

测试结果如下:

    public void openAiTest() throws IOException {
        String res = OpenAI.doChatGPT("帮我写一个冒泡排序");
        logger.info("测试结果:{}", res);
    }

在这里插入图片描述

遇到 "Cannot connect to host www.heima.com:443 ssl:default [remote computer refused the network connection]" 这样的错误,通常表示你无法通过SSL/TLS协议访问Heima网站。这可能是由于网络连接问题、防火墙限制、目标服务器问题或者是你的代码配置有问题。 以下是针对这个问题修改代码的一些建议: 1. 检查网络连接:确认你的设备能够正常访问互联网,尤其是HTTPS流量。 2. 禁用SSL验证:如果你确定可以接受非安全连接,可以临时禁用ssl验证,但这种方式不推荐因为可能存在数据传输风险,只适合测试环境。修改`aiohttp`请求部分,添加`verify_ssl=False`: ```python async with aiohttp.ClientSession(verify_ssl=False) as session: async with session.get(url) as response: ``` 3. 调整超时设置:增加连接超时时间,有时网络波动可能导致连接等待过久而失败,你可以增加`timeout`参数: ```python async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) as session: ``` 4. 检查代理设置:如果你使用了代理服务器,确保其可用并且正确配置。 5. 重试机制:对于网络不稳定的情况,可以在请求失败后添加重试逻辑。 6. 检查目标地址:确保URL `www.heima.com:443` 正确无误,可能网站已经更改了地址或端口。 记住,在生产环境中,建议保持默认的SSL验证,解决网络问题或直接联系Heima的技术支持以解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值