C/C++用万恶的libcurl透过HTTPS发POST+JSON请求

相比python, nodejs这样的脚本开发语言已有非常好用的RESTful开发库,很多C/C++程序在调用RESTful接口时,还在使用非常难使用的libcurl纯C接口。下面是用libcurl透过HTTPS发POST请求的代码代段,http body是json字符串:

    #include <curl/curl.h>

    CURL* curl;
    struct curl_slist* headers;
    curl = curl_easy_init();
    headers_ = curl_slist_append(headers, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "PEM");
    curl_easy_setopt(curl, CURLOPT_SSLCERT, cert_file_path.c_str());
    curl_easy_setopt(curl, CURLOPT_SSLKEYTYPE, "PEM");
    curl_easy_setopt(curl, CURLOPT_SSLKEY, key_file_path.c_str());
    curl_easy_setopt(curl, CURLOPT_CAINFO, ca_file_path.c_str());
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1L);

    // jv_text存了json字符串
    curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, jv_text.c_str());
    curl_easy_setopt(curl_, CURLOPT_URL, path.c_str());

    CURLcode res = curl_easy_perform(curl_);
    if (res != CURLE_OK)   // 没有成功
    {
        LG_ERR("curl_easy_perform() failed: %s", curl_easy_strerror(res));
    }
    else  // 成功了
    {
    }
    curl_easy_cleanup(curl);

Leave a Reply

Your email address will not be published. Required fields are marked *