libcurl进行post

libcurl进行post
main函数,初始化和清理curl

// 全局初始化curl
curl_global_init(CURL_GLOBAL_ALL);  

std::string url = "http://xxxx";
std::string postParams = "aa=33&bb=33";
std::string response;

curl_post_req("http://sss", "aa=33&bb=33", response);

// 程序结束前清理curl

curl_global_cleanup();  

发请求,设置参数,传入url、post参数、响应
检查response_code

bool curl_post_req(const std::string &url, const std::string &postParams, std::string &response)  
{  
    
    CURL *curl = curl_easy_init();  
    CURLcode res;  
    if (curl)  
    {  
        // set params  
        curl_easy_setopt(curl, CURLOPT_POST, 1);
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_call_back);  
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);  
        
        // start req  
        res = curl_easy_perform(curl);  
        if (res != CURLE_OK) {

            LOG(NOTICE) << "curl_easy_perform() failed: " + std::string(curl_easy_strerror(res));      
            return false;
        }  

        long response_code = 0;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
        
        if (response_code < 200 || response_code >= 300 || response.empty()) {

            LOG(WARNING) << "http failed code: " << response_code;      
            return false;
        }
        else {

            LOG(NOTICE) << "http success code: " << response_code;
        }

    }  
    // release curl  
    curl_easy_cleanup(curl);  
    return true;  
}  

回调函数

size_t write_call_back(void *contents, size_t size, size_t nmemb, std::string *userp) {

    userp->append((char *) contents, size * nmemb);
    return size * nmemb;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值