C++使用curl进行GET,POST,PUT,DELETE请求

//注意回调函数不能是普通的成员函数
static size_t getUrlResponse(void* buffer, size_t size, size_t count, void* response)
{
    std::string* str = (std::string*)response;
    (*str).append((char*)buffer, size * count);

    return size * count;
}

std::string requestMethod(const std::string url, const std::string method, const std::string request) {
    CURL* curl = curl_easy_init();
    //CURLcode res;
    std::string response;
    if (curl) {
        struct curl_slist* header_list = NULL;
        header_list = curl_slist_append(header_list, "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
        header_list = curl_slist_append(header_list, "Content-Type:application/json");

        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);
        curl_easy_setopt(curl, CURLOPT_HEADER, 0);
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

        if (method == "POST") {
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.c_str());
        }
        else if (method == "PUT") {
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.c_str());
            curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method.c_str());
        }
        else if (method == "DELETE") {
            curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method.c_str());
        }

        curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getUrlResponse);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&response);
        //如果是https请求,需要加上以下两句,否则可能会出问题,请根据个人需求添加
	    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);//设定为不验证证书和HOST 
	    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); 
        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 6);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 6);

        curl_easy_perform(curl);
    }
    curl_easy_cleanup(curl);
    return response;
}
  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值