libcurl第三课 HTTP获取天气信息

场景说明
       从 t.weather.sojson.com网页中获取天气信息。如果不使用libcurl库,需要实现Transfer-Encoding: chunked分块接收和Content-Encoding: gzip解压,现在提供libcurl实现代码


代码
size_t WriteResponseBody(void *ptr, size_t size, size_t nmemb, void *userData)
{
 std::string* pStrBuffer = (std::string*)userData;
 size_t nLen = size * nmemb;
 pStrBuffer->append((char*)ptr, nLen);
 return nLen;
}
int GetWeatherUsingCurl(const std::string &strUrl, std::string& strResponseData)
{
 CURL *pCurlHandle = curl_easy_init();
 curl_easy_setopt(pCurlHandle, CURLOPT_CUSTOMREQUEST, "GET");
 curl_easy_setopt(pCurlHandle, CURLOPT_URL, strUrl.c_str());
 curl_easy_setopt(pCurlHandle, CURLOPT_WRITEFUNCTION, WriteResponseBody);//设置回调函数
 //curl_easy_setopt(pCurlHandle, CURLOPT_HEADER, 1);//保存HTTP头部信息到strResponseData
 curl_easy_setopt(pCurlHandle, CURLOPT_WRITEDATA, &strResponseData);//设置回调函数的参数,获取反馈信息
 curl_easy_setopt(pCurlHandle, CURLOPT_TIMEOUT, 15);//接收数据时超时设置,如果10秒内数据未接收完,直接退出
 curl_easy_setopt(pCurlHandle, CURLOPT_MAXREDIRS, 1);//查找次数,防止查找太深
 curl_easy_setopt(pCurlHandle, CURLOPT_CONNECTTIMEOUT, 5);//连接超时,这个数值如果设置太短可能导致数据请求不到就断开了
 CURLcode nRet = curl_easy_perform(pCurlHandle);
 curl_easy_cleanup(pCurlHandle);
 return nRet;
}


调用例子
 std::string strResponseData;
 GetWeatherUsingCurl("t.weather.sojson.com/api/weather/city/101200101", strResponseData);


猜你喜欢

转载自blog.51cto.com/fengyuzaitu/2433592
今日推荐