場景說明
從 t.weather.sojson.com網頁中獲取天氣信息。若是不使用libcurl庫,須要實現Transfer-Encoding: chunked分塊接收和Content-Encoding: gzip解壓,如今提供libcurl實現代碼json
代碼
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;
}api
調用例子
std::string strResponseData;
GetWeatherUsingCurl("t.weather.sojson.com/api/weather/city/101200101", strResponseData);app