1. 首页
  2. 编程语言
  3. C++ 
  4. 如何使用C++代码调用https接口

如何使用C++代码调用https接口

上传者: 2023-06-07 03:56:01上传 ZIP文件 140.26MB 热度 17次

如果你已经在VS2015中编译好了curl和openssl,那么你可以使用以下代码来调用https接口:

// 引用curl库
#include <curl/curl.h>

// 定义回调函数
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

int main(void) {
    CURL *curl;
    CURLcode res;

    // 初始化curl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if (curl) {
        std::string response_str;
        // 设置url和回调函数
        curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_str);
        // 执行请求
        res = curl_easy_perform(curl);
        // 检查请求结果
        if (res != CURLE_OK) {
            std::cout << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        } else {
            std::cout << response_str << std::endl;
        }
        // 释放curl
        curl_easy_cleanup(curl);
    }
    // 清理全局curl资源
    curl_global_cleanup();
    return 0;
}

使用以上代码,你可以通过https协议调用API接口了。注意,需要在编译时链接curl和openssl库。

下载地址
用户评论