c++怎么用libcurl发送一个HTTPS请求_C++网络请求与HTTPS通信示例

使用libcurl可实现C++ HTTPS请求。首先安装开发库,然后编写代码:包含头文件,定义写入回调函数,初始化curl,设置URL、SSL验证、超时、用户代理及回调函数,执行请求并处理响应,最后清理资源。编译时链接-libcurl。支持GET、POST及自定义请求头,注意证书验证与CA路径配置。

要用C++发送HTTPS请求,libcurl 是最常用的库之一。它支持多种协议,包括HTTP、HTTPS,并且跨平台。下面是一个完整的示例,展示如何使用 libcurl 发送一个简单的 HTTPS GET 请求,并验证 SSL 证书。

1. 安装 libcurl

在使用之前,确保系统已安装 libcurl 开发库:
  • Ubuntu/Debian:运行 sudo apt-get install libcurl4-openssl-dev
  • CentOS/RHEL:运行 sudo yum install curl-devel
  • Windows:可通过 vcpkg 安装:vcpkg install curl,或下载预编译版本并配置到项目中

2. 编写 HTTPS GET 请求代码

以下是一个使用 libcurl 发送 HTTPS 请求的 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 = 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;
}

3. 编译与链接

编译时需要链接 curl 库。例如使用 g++:
g++ -o https_request https_request.cpp -lcurl

运行程序:

./https_request

4. 常见问题与注意事项

  • 证书路径问题:在某些系统上,可能需要手动指定 CA 证书路径:
    curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/cacert.pem");
  • 关闭证书验证(仅测试):不推荐生产环境使用: curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  • POST 请求:只需添加: curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=value&foo=bar");
  • 设置请求头:例如 JSON 请求:
    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 请求。