C++使用cURL发送Discord Webhook消息报无法发送空消息错误
问题成因
返回Cannot send an empty message错误的核心原因是请求不符合Discord Webhook的接口规范,对比可正常运行的命令行curl命令,代码缺失两个关键配置:
- 未设置正确的请求头:命令行请求明确指定了
Content-Type:application/json,但libcurl发送POST请求时默认使用application/x-www-form-urlencoded作为Content-Type,Discord服务端会按表单格式解析请求体,无法识别JSON结构内容。 - 请求体格式错误:直接将纯字符串
test作为POST内容发送,但Discord Webhook要求请求体必须是标准JSON格式,消息内容必须放在content字段下,纯文本内容没有这个字段,服务端读取不到有效消息内容,就会判定为空消息返回50006错误。
修复方法
对应调整两处配置即可:
- 给libcurl添加JSON格式的请求头
- 把待发送内容拼接成符合要求的JSON结构作为请求体
修复后的可运行代码如下:
#include <iostream> #include <curl/curl.h> int main(void) { CURL* curl; CURLcode res; const char* WEBHOOK = "替换为你的实际Webhook地址"; // 转义JSON中的双引号,构造符合要求的请求体 const char* post_data = "{\"content\": \"test\"}"; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { // 构造JSON请求头 struct curl_slist* headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "Accept: application/json"); curl_easy_setopt(curl, CURLOPT_URL, WEBHOOK); // 绑定请求头 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // 传入构造好的JSON请求体 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); res = curl_easy_perform(curl); if (res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); // 释放请求头资源 curl_slist_free_all(headers); curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; }
注意事项
- 如果发送的内容包含双引号、换行等特殊字符,需要提前做JSON转义,否则会触发JSON格式解析错误
- 编译时需要链接libcurl库,g++编译参考命令:
g++ send_msg.cpp -o send_msg -lcurl
内容的提问来源于stack exchange,提问作者Antonizz
相关产品推荐
相关产品推荐

