首先安装配置libcurl库,然后通过其API发送HTTP请求。Linux用apt-get、macOS用brew、Windows用vcpkg等方式安装,编译时链接-lcurl。使用curl_easy_init初始化,curl_easy_setopt设置选项,如URL、回调函数WriteCallback接收数据,curl_easy_perform执行请求,最后curl_easy_cleanup清理资源。GET请求示例中,设置CURLOPT_URL为目标地址,CURLOPT_WRITEFUNCTION为WriteCallback,将响应写入字符串。POST请求需设置CURLOPT_POST为1L,CURLOPT_POSTFIELDS为表单或JSON数据,若发JSON需添加Content-Type头。可设CURLOPT_TIMEOUT和CURLOPT_CONNECTTIMEOUT控制超时,CURLOPT_USERAGENT模拟浏览器。多线程下每个线程应独立创建CURL句柄,注意错误处理与资源释放。

在C++中使用libcurl发送HTTP请求,需要先安装并配置libcurl库,然后调用其提供的API来完成GET、POST等请求。下面介绍基本的使用方法和代码示例。
1. 安装和配置libcurl
在使用前确保已正确安装libcurl:
- Linux(Ubuntu/Debian):运行 sudo apt-get install libcurl4-openssl-dev
- macOS:使用Homebrew: brew install curl
- Windows:可通过vcpkg或下载预编译库,或使用MinGW/MSYS2安装
编译时需链接curl库,例如g++命令:
g++ main.cpp -lcurl
2. 基本HTTP GET请求
以下是一个简单的GET请求示例:
立即学习“C++免费学习笔记(深入)”;
#include#include #include // 回调函数:接收响应数据 size_t WriteCallback(void contents, size_t size, size_t nmemb, std::string output) { size_t totalSize = size nmemb; output->append((char)contents, totalSize); return totalSize; }
int main() { CURL* curl; CURLcode res; std::string readBuffer;
curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/get"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); res = curl_easy_perform(curl); if (res != CURLE_OK) { std::cerr << "请求失败: " << curl_easy_strerror(res) << std::endl; } else { std::cout << "响应内容:\n" << readBuffer << std::endl; } curl_easy_cleanup(curl); } return 0;}
3. 发送POST请求
发送表单或JSON数据可以使用POST方法:
curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/post"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=John&age=30"); // 或发送JSON // curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"name\":\"John\", \"age\":30}"); curl_easy_setopt(curl, CURLOPT_POST, 1L);如果发送JSON,建议设置Content-Type头:
struct curl_slist* headers = nullptr; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);记得最后用 curl_slist_free_all(headers); 释放头信息。
4. 设置超时和用户代理
为避免长时间等待,可设置超时时间:
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); // 总超时(秒) curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L); // 连接超时模拟浏览器请求,可设置User-Agent:
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible)");基本上就这些。初始化、设置选项、执行请求、清理资源,是libcurl的标准流程。掌握WriteCallback和常用opt设置后,就能灵活处理各种HTTP场景。注意线程安全问题,多线程下每个线程应使用独立的CURL句柄。不复杂但容易忽略错误处理和资源释放。











