C++使用libcurl调用接口返回数据

1.环境配置

首先在网上要下载对应的libcurl库,然后在项目中引用这些库。下载的库文件应包括这些
C++使用libcurl调用接口返回数据_第1张图片
然后在项目中配置环境:
1.引用头文件
C++使用libcurl调用接口返回数据_第2张图片
2.链接静态库
C++使用libcurl调用接口返回数据_第3张图片
C++使用libcurl调用接口返回数据_第4张图片

3.动态库需放在生成的debug或release目录中

2.相关函数封装

get函数:

static size_t WriteDataCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
    try
    {
        size_t realsize = size * nmemb;
        static int current_index = 0;
        int content_size = nmemb * size;
        std::string result = std::string((char*)contents, content_size);
        string* pStr = (string*)userp;
        if (pStr)
        {
            (*pStr).append(result);
        }
        return realsize;
    }
    catch (...)
    {

    }
    return 0;
}

CURLcode HttpGet(const std::string& url,std::string& response, int timeout = 300)
{
    CURLcode return_code, res;
    return_code = curl_global_init(CURL_GLOBAL_WIN32);
    if (CURLE_OK != return_code)
    {
        return CURLE_FAILED_INIT;
    }
    // 获取easy handle
    CURL* easy_handle = curl_easy_init();
    if (NULL == easy_handle)
    {
        curl_global_cleanup();
        return CURLE_FAILED_INIT;
    }
    // 设置easy handle属性
    curl_easy_setopt(easy_handle, CURLOPT_URL, url.c_str());
    curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, WriteDataCallback);
    curl_easy_setopt(easy_handle, CURLOPT_TIMEOUT, timeout);
    curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, (void*)&response);
    // 执行数据请求
    res = curl_easy_perform(easy_handle);
    curl_easy_cleanup(easy_handle);
    curl_global_cleanup();
    return res;

}

2.post函数

size_t ReceiveData(void* contents, size_t size, size_t nmemb, void* stream)
{
    std::string* str = (std::string*)stream;
    (*str).append((char*)contents, size * nmemb);
    return size * nmemb;
}

CURLcode HttpPost(const std::string& url, const std::string& data, std::string& response, int timeout = 300)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    struct curl_slist* headers = NULL;
    headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");

    if (curl == NULL)
    {
        return CURLE_FAILED_INIT;
    }

    // 设置请求地址
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    // 设置请求头信息
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    // 不显示接收头信息
    curl_easy_setopt(curl, CURLOPT_HEADER, 0);
    // 设置请求超时时间
    curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeout);
    // 设置请求体
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
    // 设置接收函数
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ReceiveData);
    // 设置接收内容
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&response);

    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    return res;
}

你可能感兴趣的:(C++,c++,java,算法)