struct V3MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct V3MemoryStruct *mem = (struct V3MemoryStruct *)userp; char *ptr = (char *)realloc(mem->memory, mem->size + realsize + 1); if(ptr == NULL) { /* out of memory! */ printf("not enough memory (realloc returned NULL) "); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; }
void EW_HandleV3Url(APIV3_REQUEST_TYPE type,char *url,Json::Value &resultjson) { struct V3MemoryStruct chunk; chunk.memory = (char *)malloc(sizeof(char)); /* will be grown as needed by the realloc above */ chunk.size = 0; /* no data at this point */ //if(type == APIV3_SEARCH_TYPE) { curl_global_init(CURL_GLOBAL_ALL); CURL *curl = NULL; curl = curl_easy_init(); if(curl == NULL) { printf("curl is NULL. "); curl_global_cleanup(); return ; } curl_easy_setopt(curl, CURLOPT_URL,url); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER,0);//跳过ssl证书 从机 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);//跳过ssl 证书 主机 curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);//使用IPV4地址 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);//将一些请求参数输出到控制台 类似如打印 curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,WriteMemoryCallback);//请求 返回的数据回调函数指针 curl_easy_setopt(curl,CURLOPT_WRITEDATA,(void *)&chunk);//请求 返回数据的buffer curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,15000); CURLcode res = CURLE_FAILED_INIT; res = curl_easy_perform(curl); if(res != CURLE_OK) printf("curl_easy_perform() failed: %s ",curl_easy_strerror(res)); else printf("%lu bytes retrieved ",(unsigned long)chunk.size); if(chunk.size <=0) { printf("recv data have problem.please check curl flow. "); return; } //json parse start if(type == APIV3_SEARCH_TYPE) { // } else {//most popular part } //json parse end /* always cleanup */ curl_easy_cleanup(curl); free(chunk.memory); curl_global_cleanup(); } }