C++ 调用 libcurl 发送 HTTP 请求需初始化句柄、设置选项、执行请求、处理响应并清理资源;其为 C 风格 API,稳定适合生产环境,支持 GET/POST 及状态码获取。

用 C++ 调用 libcurl 发送 HTTP 请求,核心是初始化 curl 句柄、设置选项、执行请求、处理响应、清理资源。它不是开箱即用的“类库”,而是 C 风格 API,但封装得清晰稳定,适合生产环境。
1. 安装与基础配置
Linux(如 Ubuntu)直接安装开发包:
sudo apt install libcurl4-openssl-dev
macOS 用 Homebrew:
立即学习“C++ 免费学习笔记(深入)”;
brew install curl
Windows 推荐用 vcpkg:
vcpkg install curl:x64-windows
然后在 CMakeLists.txt 中链接 curl 库,并确保包含头文件路径。
代码开头必须包含:
#include
2. GET 请求(带超时和错误检查)
这是最常用场景。关键点:必须设置 CURLOPT_URL、CURLOPT_FOLLOWLOCATION(重定向)、CURLOPT_TIMEOUT(防卡死),并提供 回调函数 接收响应体。
示例代码片段:
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {size_t realsize = size * nmemb; std::string* buf = static_cast(userp); buf->append(static_cast(contents), realsize); return realsize; } std::string httpGet(const std::string& url) {CURL* curl; CURLcode res; std::string response;
curl = curl_easy_init(); if (!curl) return ""; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); curl_easy_setopt(curl, CURLOPT_USERAGENT,"cpp-libcurl/1.0"); res = curl_easy_perform(curl); if (res != CURLE_OK) {fprintf(stderr,"curl_easy_perform() failed: %sn", curl_easy_strerror(res)); } curl_easy_cleanup(curl); return response;
}
3. POST 请求(JSON 数据)
发送 JSON 时需手动设置 Content-Type 头,并把 JSON 字符串作为 POST body。注意:libcurl 默认不自动识别 JSON,必须显式设置头和数据指针。
- 用 CURLOPT_POSTFIELDS 传原始字符串(适合小数据)
- 用 CURLOPT_POST 启用 POST 方法(或更推荐 CURLOPT_CUSTOMREQUEST + CURLOPT_POSTFIELDS 组合)
- 用 CURLOPT_HTTPHEADER 添加自定义 header(如 application/json)
示例:
std::string httpPostJson(const std::string& url, const std::string& json) {CURL* curl; CURLcode res; std::string response; curl = curl_easy_init(); if (!curl) return ""; struct curl_slist* headers = nullptr; headers = curl_slist_append(headers,"Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, json.length()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); res = curl_easy_perform(curl); if (res != CURLE_OK) {fprintf(stderr,"POST failed: %sn", curl_easy_strerror(res)); } curl_slist_free_all(headers); curl_easy_cleanup(curl); return response;
}
4. 处理状态码与常见错误
仅靠 curl_easy_perform() 返回值不够——它只表示网络层是否成功(如 DNS 解析、连接、发送)。要获取 HTTP 状态码(如 404、500),必须调用 curl_easy_getinfo():
long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); if (http_code == 200) {// 成功} else if (http_code>= 400) {// 客户端或服务端错误}
常见失败原因:
- CURLE_COULDNT_RESOLVE_HOST:域名解析失败 → 检查网络或 DNS
- CURLE_COULDNT_CONNECT:无法建立 TCP 连接 → 检查目标地址、端口 、 防火墙
- CURLE_OPERATION_TIMEDOUT:超时 → 调大 CURLOPT_TIMEOUT 或检查服务可用性
- 返回空响应但无报错 → 很可能是未设置 CURLOPT_FOLLOWLOCATION 导致 302 重定向被忽略
不复杂但容易忽略。






























