使用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 <iostream>
#include <string>
#include <curl/curl.h>
// 回调函数:接收响应数据
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_VERIFYPEER, 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 请求。
以上就是c++++怎么用libcurl发送一个HTTPS请求_C++网络请求与HTTPS通信示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号