size_t getUrlResponse(void *buffer, size_t size, size_t count, void *response)
{
    string *str = (string*)response;
    (*str).append((char*)buffer, size*count);

    return size * count;
}

//post请求
string setRequest(string url, string data)
{
    string response = "";

    CURL *curl = NULL;
    struct curl_slist *headers = NULL;//报文头
    curl_global_init(CURL_GLOBAL_ALL);

    curl = curl_easy_init();

    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charsets: utf-8");

    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());

    //    curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
    //    curl_easy_setopt(curl, CURLOPT_HEADER, 0L);

    // 注册回调函数 获取信息
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &getUrlResponse);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

    int res = curl_easy_perform(curl);

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return response;
}

//get请求
string getRequest(string url)
{
    // 请求数据
       string response = "";

       CURL *curl = NULL;
       struct curl_slist *headers = NULL;
       curl_global_init(CURL_GLOBAL_ALL);

       curl = curl_easy_init();

       headers = curl_slist_append(headers, "Accept: application/json");
       headers = curl_slist_append(headers, "Content-Type: application/json");
       headers = curl_slist_append(headers, "charsets: utf-8");

       // 设置url
       curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
       curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
       curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
       curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
       // 注册回调函数 获取信息
       curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &getUrlResponse);
       curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

       // 执行请求
       curl_easy_perform(curl);
       // 释放
       curl_easy_cleanup(curl);
       curl_global_cleanup();

       return response;
}

解析:
string info = 请求函数;

#include <jsoncpp/json/json.h>
Json::Reader jreader;
Json::Value jvalue;
jreader.parse(info, jvalue);
string res = jvalue["errcode"].asString().c_str();
cout<<"errcode = "<<res<<endl;//得到得返回中得code是200还是多少

 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐