libcurl用法

本文以向百度搜索开放平台搜索关键字所对应的推荐搜索条目为例子:

url:http://m.baidu.com/su?wd=%s&action=opensearch&ie=utf-8

(%s带上所要搜索的关键字)

reponse:返回推荐搜索条目的JSON格式数据

【举例】

url:http://m.baidu.com/su?wd=iphone&action=opensearch&ie=utf-8

response:["iphone",["iphone6","iphone6plus","iphone5s","iphone6s","iphone5","iphone4s","iphone7","iphone5c","iphone4","iphone6 plus"]]

 

#define URL_TEMPLATE_SQ "http://m.baidu.com/su?wd=%s&action=opensearch&ie=utf-8"



char *keyword = ***;//iphone



curl_global_init(CURL_GLOBAL_ALL);



CURL *curl;

CURLcode curl_code;



curl = curl_easy_init();



if (!curl)

{

    PERR("Failed to initial CURL connection\n");

    curl_global_cleanup();

    return ERR_CODE;

}



char content[URL_SIZE];

memset(content, 0x00, sizeof(content));

sprintf(content, URL_TEMPLATE_SQ, keyword);



curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);//get方式

curl_easy_setopt(curl, CURLOPT_URL, content);//填入url

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _write_data);//server发回response的时候的回调函数

curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);

curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT , 10);

curl_easy_setopt(curl, CURLOPT_WRITEDATA , keyword);//带入的用户数据,在回调函数中送回,即*user_p



curl_code = curl_easy_perform(curl);



if(curl_code != CURLE_OK)

{

    PLOG("error curl_code is %d", curl_code);

    ret = ERR_CODE;

    goto EXIT;

}



EXIT:

curl_easy_cleanup(curl);

curl_global_cleanup();

 

回调函数如下:

static size_t _write_data(void *ptr, size_t size, size_t nmemb, void *user_p)

{

    long total_size = size * nmemb;

    LOG("get %d bytes from server", total_size);

    char *response_data = NULL;



    if(ptr == NULL)

    {

        PERR("ptr is NULL");

        return -1;

    }else

    {

        response_data = (char *)ptr;

        LOG("[data] %s", response_data);

    }



    char *keyword = (char *)user_p;//用户数据,即“iphone”



    //TODO 用户做一些事情,比如用libjson来解析成字符串数组然后填满列表



    return total_size;

}

 

你可能感兴趣的:(curl)