在 C++ 中发送短信:使用 LibCurl 库进行 API 调用的完整指南
发送短信是现代应用程序的关键功能之一,从双因素认证到订单状态通知。C++ 生态系统中没有用于与短信网关交互的内置工具,但借助通用库 libcurl 和标准 HTTP 请求,可以轻松集成任何 REST API 短信提供商。在本文中,我们将介绍如何使用 LibCurl 库在 C++ 中编写一个可靠的短信发送函数,并针对流行服务(Twilio、SMS Aero、Bytehand)提供典型示例。
为什么选择 LibCurl?
LibCurl 是一个跨平台的数据传输库,支持多种协议(HTTP、HTTPS、FTP 等)。它支持:
- GET、POST、PUT、DELETE 请求
- SSL/TLS(HTTPS)
- 处理请求头和请求体
- 处理服务器响应
要发送短信,只需向所选提供商的 API 发送 POST 请求,并传递必要的参数(电话号码、文本、API 密钥)。LibCurl 负责所有底层套接字和加密工作。
安装库
在大多数 Linux 发行版中,可以通过包管理器安装 LibCurl:
sudo apt-get install libcurl4-openssl-dev # Ubuntu/Debiansudo yum install libcurl-devel # CentOS/RHEL对于 Windows,可以从官方网站下载预编译的 DLL,或使用 vcpkg:
vcpkg install curl在代码中引用:
#include <curl/curl.h>#include <string>#include <json/json.h> // 如果使用 JSON(nlohmann/json)短信函数的基本结构
我们将创建一个通用函数 sendSms,它接受 API URL、密钥、收件人号码和消息文本。为了方便处理 JSON,建议使用 nlohmann/json 库(仅头文件,无需编译)。
#include <iostream>#include <string>#include <curl/curl.h>#include <nlohmann/json.hpp>
using json = nlohmann::json;
// 用于写入服务器响应的回调函数static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb;}
bool sendSms(const std::string& url, const std::string& apiKey, const std::string& phone, const std::string& message) { CURL *curl; CURLcode res; std::string readBuffer;
curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init();
if(!curl) return false;
// 构建 JSON 请求体 json payload; payload["phone"] = phone; payload["text"] = message; payload["api_key"] = apiKey;
std::string jsonStr = payload.dump();
// 配置 HTTP 请求 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, url.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonStr.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// 执行请求 res = curl_easy_perform(curl);
// 清理 curl_easy_cleanup(curl); curl_global_cleanup();
if(res != CURLE_OK) { std::cerr << "curl 错误: " << curl_easy_strerror(res) << std::endl; return false; }
// 解析响应(以 Twilio 为例) try { json response = json::parse(readBuffer); if(response.co