You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用OpenAI Completions API时URL格式错误致FileNotFoundException求助

问题排查与修复方案

核心问题分析

  • 请求方法错误:OpenAI的/v1/completions接口仅支持POST请求,你的代码使用了GET,这是触发FileNotFoundException的主要原因——当GET请求被接口拒绝时会返回405状态码,此时调用conn.getInputStream()会抛出该异常。
  • 参数传递方式错误:Completions接口的参数(如model、prompt)需要放在JSON格式的请求体中,而非URL查询参数。GET请求的URL长度有限,且接口本身不支持这种传参方式。
  • 缺少必要请求头:POST请求必须设置Content-Type: application/json,否则接口无法正确解析请求体。
  • 未处理错误响应:当接口返回非200状态码时,直接调用getInputStream()会抛出异常,应该先判断响应码,通过getErrorStream()获取具体错误信息。

修改后的代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ChatGPT {

    public static void main(String[] args) throws IOException {
        String prompt = "What country has the most moderate weather?";
        String model = "text-curie-001";
        String apiKey = /* 你的API密钥 */;

        // 构造请求URL
        URL url = new URL("https://api.openai.com/v1/completions");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 设置请求方法为POST,开启输出流
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        // 设置必要请求头
        conn.setRequestProperty("Authorization", "Bearer " + apiKey);
        conn.setRequestProperty("Content-Type", "application/json");

        // 构造JSON请求体,转义双引号避免格式错误
        String requestBody = String.format(
            "{\"model\":\"%s\", \"prompt\":\"%s\", \"max_tokens\":100}",
            model,
            prompt.replace("\"", "\\\"")
        );

        // 发送请求体
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = requestBody.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        // 根据响应状态码选择读取流
        int responseCode = conn.getResponseCode();
        BufferedReader reader;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }

        // 读取响应内容
        StringBuilder responseBody = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            responseBody.append(line);
        }
        reader.close();

        // 打印响应信息
        System.out.println("响应状态码: " + responseCode);
        System.out.println("响应内容: " + responseBody);
    }
}

关键修改说明

  1. 切换为POST请求:将请求方法改为POST,并开启输出流以写入请求体。
  2. JSON请求体传参:把参数封装成JSON字符串传入,同时转义字符串中的双引号,避免JSON格式错误。
  3. 添加Content-Type头:明确告诉接口请求体的格式为JSON,确保解析正常。
  4. 错误响应处理:先判断响应状态码,根据结果选择读取正常流或错误流,既能避免异常,也能查看具体错误详情。

内容的提问来源于stack exchange,提问作者Isaac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 00:40:18