溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

libcurl第三課 HTTP獲取天氣信息

發(fā)布時間:2020-06-27 17:55:54 來源:網(wǎng)絡(luò) 閱讀:407 作者:fengyuzaitu 欄目:軟件技術(shù)

場景說明
?????? 從 t.weather.sojson.com網(wǎng)頁中獲取天氣信息。如果不使用libcurl庫,需要實現(xiàn)Transfer-Encoding: chunked分塊接收和Content-Encoding: gzip解壓,現(xiàn)在提供libcurl實現(xiàn)代碼


代碼
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);//設(shè)置回調(diào)函數(shù)
?//curl_easy_setopt(pCurlHandle, CURLOPT_HEADER, 1);//保存HTTP頭部信息到strResponseData
?curl_easy_setopt(pCurlHandle, CURLOPT_WRITEDATA, &strResponseData);//設(shè)置回調(diào)函數(shù)的參數(shù),獲取反饋信息
?curl_easy_setopt(pCurlHandle, CURLOPT_TIMEOUT, 15);//接收數(shù)據(jù)時超時設(shè)置,如果10秒內(nèi)數(shù)據(jù)未接收完,直接退出
?curl_easy_setopt(pCurlHandle, CURLOPT_MAXREDIRS, 1);//查找次數(shù),防止查找太深
?curl_easy_setopt(pCurlHandle, CURLOPT_CONNECTTIMEOUT, 5);//連接超時,這個數(shù)值如果設(shè)置太短可能導(dǎo)致數(shù)據(jù)請求不到就斷開了
?CURLcode nRet = curl_easy_perform(pCurlHandle);
?curl_easy_cleanup(pCurlHandle);
?return nRet;
}


調(diào)用例子
?std::string strResponseData;
?GetWeatherUsingCurl("t.weather.sojson.com/api/weather/city/101200101", strResponseData);


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI