使用libcurl可实现C++ HTTPS请求。首先安装开发库,然后编写代码:包含头文件,定义写入回调函数,初始化curl,设置URL、SSL验证、超时、用户代理及回调函数,执行请求并处理响应,最后清理资源。编译时链接-libcurl。支持GET、POST及自定义请求头,注意证书验证与CA路径配置。
要用C++发送HTTPS请求,libcurl 是最常用的库之一。它支持多种协议,包括HTTP、HTTPS,并且跨平台。下面是一个完整的示例,展示如何使用 libcurl 发送一个简单的 HTTPS GET 请求,并验证 SSL 证书。
sudo apt-get install libcurl4-openssl-dev
sudo yum install curl-devel
vcpkg install curl,或下载预编译版本并配置到项目中#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 = curl_easy_init(); if (!curl) { std::cerr << "curl 初始化失败" << std::endl; return 1; } // 设置请求 URL(必须是 https) curl_easy_setopt(curl, CURLOPT_URL, "https://httpbin.org/get"); // 启用 SSL 验证(推荐) curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); // 验证服务器证书 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); // 验证主机名 // 设置超时 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); // 设置用户代理 curl_easy_setopt(curl, CURLOPT_USERAGENT, "MyCppApp/1.0"); // 设置写入回调函数 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; }
g++ -o https_request https_request.cpp -lcurl
运行程序:
./https_request
curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/cacert.pem");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEE
R, 0L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=value&foo=bar");
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);
基本上就这些。只要正确配置 SSL 和回调函数,libcurl 能稳定地处理 HTTPS 请求。