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

C++使用nlohmann_json和libcurl发Webhook报50006空消息错误如何解决

问题产生原因
  • 缺少Content-Type请求头:libcurl发送POST请求默认使用application/x-www-form-urlencoded格式,接口无法正确解析JSON格式的请求体,因此识别不到你提交的embeds字段,判定请求内容为空,返回50006错误。
  • 存在悬空指针风险:data.dump()会生成一个临时的std::string对象,调用data()获取指针后临时对象会立即销毁,libcurl读取的是已经释放的非法内存,可能出现传空、乱码等异常。
  • 可选问题:部分Webhook实现不支持embeds中color字段为null,也可能触发参数校验错误。
修复方案

按如下步骤修改代码即可:

  1. 提前保存序列化后的JSON字符串,避免临时对象销毁问题
  2. 添加Content-Type: application/json请求头,告诉接口按JSON格式解析请求
  3. 可选:移除color字段或者赋值为合法的整数颜色值(如0代表黑色)

修正后的完整代码示例

#include <nlohmann/json.hpp>
#include <curl/curl.h>
#include <iostream>
using json = nlohmann::json;

int main() {
    // 构造JSON数据,移除了为null的color字段避免校验问题
    json data = R"(
        {
          "content": null,
          "embeds": [
            {
              "title": "Login",
              "description": "Key = null"
            }
          ]
        }
    )"_json;

    CURL *curl = curl_easy_init();
    CURLcode res;
    const char* webhookURL = "你的webhook地址";
    if (curl) {
        // 提前保存序列化后的JSON字符串
        std::string post_data = data.dump();
        // 设置请求头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        
        curl_easy_setopt(curl, CURLOPT_URL, webhookURL);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        // 传入持久化的字符串指针,显式设置长度避免依赖终止符
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post_data.size());

        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cout << curl_easy_strerror(res) << std::endl;
        }
        // 释放资源
        curl_easy_cleanup(curl);
        curl_slist_free_all(headers);
    }
    curl_global_cleanup();
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:45:03