libcURL 在QT中的使用
useCurl函数中为使用 curl 代码
int getWeather::useCurl(){ if(_area_Str.isNull()) { return 0; } QString url = "http://apis.baidu.com/showapi_open_bus/weather_showapi/address"+_area_Str; QByteArray ba ; ba = url.toLocal8Bit(); char * m_url = ba.data(); CURL *curl; CURLcode res; /* In windows, this will init the winsock stuff */ curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "apikey: xxxxxxxxxxxxxxxxxxx"); if(curl) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);// 改协议头 curl_easy_setopt(curl, CURLOPT_URL, m_url); /* example.com is redirected, so we tell libcurl to follow redirection */ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); char buffer[4096] = {0x0}; curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); /* always cleanup */ curl_easy_cleanup(curl); // qDebug()<<chunk.memory; curl_global_cleanup(); return 1; } return 0; }
回调函数,用于将数据写入buff中,也可以在curl 中使用
char buffer[4096] = {0x0};
curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer);
来获取buff
size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) { strcat( (char*)stream, (char*)ptr); // int written = fwrite(ptr, size, nmemb, (FILE *)fp); return size * nmemb; //必须返回这个大小, 否则只回调一次, 不清楚为何. }