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);
        
        // 释放 header_list
        curl_slist_free_all(header_list);
        curl_easy_perform(curl);
    }
    curl_easy_cleanup(curl);
    return response;
}

你可能感兴趣的:(c++,开发语言)