为什么用 libcurl

libcurl 是最流行的 C/C++ HTTP 库,支持 HTTP/HTTPS、超时、重定向、上传下载等,跨平台。

最简单的 GET

#include <curl/curl.h>
#include <string>

static size_t write_cb(void* ptr, size_t size, size_t nmemb, std::string* data) {
    data->append((char*)ptr, size * nmemb);
    return size * nmemb;
}

std::string http_get(const std::string& url) {
    CURL* curl = curl_easy_init();
    std::string resp;
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);      // 超时 10s
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // 跟随重定向
    CURLcode res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    return resp;
}

POST JSON

std::string http_post(const std::string& url, const std::string& body) {
    CURL* curl = curl_easy_init();
    std::string resp;
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
    struct curl_slist* hs = nullptr;
    hs = curl_slist_append(hs, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp);
    curl_easy_perform(curl);
    curl_slist_free_all(hs);
    curl_easy_cleanup(curl);
    return resp;
}

编译

g++ -std=c++17 client.cpp -lcurl -o client
提示:返回体解析 JSON 可用 nlohmann/json 单头文件库;HTTPS 需要链接 openssl。