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

使用C++的libcurl库无法发送JSON请求的问题排查

C++ libcurl POST请求体乱码问题排查与解决

我尝试用C++结合libcurl库向GraphQL服务器发送HTTP POST请求,使用hookbin测试端点验证请求,测试代码如下:

int main(int argc, char* argv[]) {
    CURL* handle = curl_easy_init();
    curl_easy_setopt(handle, CURLOPT_URL, "https://hookb.in/YVk7VyoEyesQjy0QmdDl");

    struct curl_slist* headers = NULL;
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charset: utf-8");
    curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);

    string data = "{\"hi\" : \"there\"}";

    cout << data << endl;
    curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data);

    CURLcode success = curl_easy_perform(handle);
    return 0;
}

预期请求体为JSON格式的{"hi": "there"},但实际请求体出现乱码。

问题原因

CURLOPT_POSTFIELDS选项要求传入const char*类型的C风格字符串,但代码中直接传入了C++ std::string对象。std::string是封装类,内部包含指针、长度等成员变量,并非直接存储字符串内容,libcurl会将其当作指针解析,读取到错误的内存区域,从而导致乱码。

解决方法

方法1:传入C风格字符串指针

调用std::string的c_str()方法,获取其内部存储的C风格字符串指针,这是最直接的解决方式:

curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());

方法2:明确指定请求体长度(可选)

如果需要确保请求期间数据的有效性(比如std::string可能被提前销毁的场景),可以同时设置CURLOPT_POSTFIELDSIZE指定数据长度:

curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, data.size());

额外优化:清理资源避免泄漏

原代码未释放curl相关资源,建议在curl_easy_perform执行完成后添加清理代码:

curl_slist_free_all(headers); // 释放请求头链表
curl_easy_cleanup(handle);    // 释放curl句柄

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:57:33