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

如何在C++的system()函数中正确编写调用OpenAI API的CURL请求?

解决C++ system()调用curl请求OpenAI API的格式问题

问题根源

你的代码存在两处关键问题:

  • 字符串转义错误:C++字符串中未正确转义JSON内部的双引号,导致shell解析命令时提前截断了JSON payload,引发curl的括号不匹配错误。
  • 无效JSON payload:错误的转义导致实际发送给OpenAI的JSON格式损坏,触发API的解析错误。

正确的代码实现

方法1:手动转义所有双引号

#include <iostream>
#include <string>

int main() {
    // 替换API_KEY为你的实际密钥
    std::string command = "curl -X POST -H \"Content-Type: application/json\" -H \"Authorization: Bearer API_KEY\" -d \"{\\\"prompt\\\": \\\"Hello, World!\\\", \\\"max_tokens\\\": 5}\" https://api.openai.com/v1/engines/davinci-codex/completions";
    int result = system(command.c_str());
    return result;
}

转义逻辑:

  • C++字符串中,用\"表示实际的双引号(用于包裹curl的参数值)。
  • JSON内部的双引号需要被shell识别为字符串的一部分,因此需要在C中写成\\\"(第一个\转义C的", 第二个\转义shell的")。

方法2:使用C++11 Raw String Literal(更简洁)

如果你的编译器支持C++11及以上,可以用原生字符串字面量避免多层转义:

#include <iostream>
#include <string>

int main() {
    // 替换API_KEY为你的实际密钥
    std::string command = R"(curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer API_KEY" -d "{\"prompt\": \"Hello, World!\", \"max_tokens\": 5}" https://api.openai.com/v1/engines/davinci-codex/completions)";
    int result = system(command.c_str());
    return result;
}

优势:原生字符串中无需转义外层双引号,仅需给JSON内部的双引号添加一个\(供shell解析),代码可读性更高。

验证说明

修正后,shell收到的完整curl命令会正确将整个JSON作为-d的参数值,curl能正确构造符合要求的JSON请求体,OpenAI API即可正常解析并返回结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:52:57