欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【踩坑记录】curl

程序员文章站 2024-02-10 08:53:40
...

c++利用libcurl发送POST请求

#include <curl/curl.h>



static int writer(char* data, size_t size, size_t nmemb, std::string* writer_data)
{ 
    unsigned long sizes = size * nmemb;
    if (NULL == writer_data){  
        return 0;
    }  
    writer_data->append(data, sizes);
    return sizes;
}

std::string getRealUrl(CURL *pCurl, std::string url){
    std::string strJsonData = getJsonData(url);//url转化为json字符串(自定义)
    std::string post_url = "XXXX";//

    CURL *curl = curl_easy_init();
    CURLcode res = curl_global_init(CURL_GLOBAL_ALL);
    curl_slist *pList = NULL;
    pList = curl_slist_append(pList,"Content-Type:application/json");
    curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, pList);
    curl_easy_setopt(pCurl, CURLOPT_URL, post_url.c_str() );
    curl_easy_setopt(pCurl, CURLOPT_HEADER, 0L);
    curl_easy_setopt(pCurl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(pCurl, CURLOPT_NOSIGNAL, 1L);
    curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, &result);    
    curl_easy_setopt(pCurl, CURLOPT_POST, 1L);
    curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, strJsonData.c_str());
    curl_easy_setopt(pCurl, CURLOPT_POSTFIELDSIZE, strJsonData.size());
    res = curl_easy_perform(pCurl);
    int res_code = 0;
    res=curl_easy_getinfo(pCurl, CURLINFO_RESPONSE_CODE, &res_code);

    Json::Reader Reader;
    Json::Value root;
    Reader.parse(result, root);
    result_url = root["resultlist"][0]["url"].toStyledString();

    curl_slist_free_all(pList);
    curl_global_cleanup();
    curl_easy_cleanup(curl);
}