libcurl進行HTTP GET獲取解析JSON數據


  • 功能
    在Mac下,利用libcurl庫進行HTTP GET操作,循環獲取json數據並解析。

  • 依賴庫

boost
libcurl
  • 代碼
#include <curl/curl.h>
#include <curl/easy.h>
#include <curl/curlbuild.h>
#include <sstream>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <ctime>

#ifdef _WINDOWS
#include <windows.h>
#else
#include <unistd.h>
#define Sleep(x) usleep((x)*1000)
#endif

using namespace std;
using namespace boost::property_tree;


size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) {
string data((const char*) ptr, (size_t) size * nmemb);
*((stringstream*) stream) << data << endl;
return size * nmemb;
}

int main(int argc, char *argv[])
{
while(true)
{
// 基於當前系統的當前日期/時間
time_t now = time(0);
char* dt = ctime(&now);
cout << dt << "-------------------------------------" << endl;

/*HTTP GET json data*/
std::stringstream out;
void* curl = curl_easy_init();
// 設置URL
curl_easy_setopt(curl, CURLOPT_URL, "http://172.21.1.121:4000/api/officeZone1/tempHum/allDevices/last");
// 設置接收數據的處理函數和存放變量
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);

// 執行HTTP GET操作
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}

// 接受數據存放在out中,輸出之
//cout << out.str() << endl;
string str_json = out.str();
curl_easy_cleanup(curl);


/*Parse json data*/
ptree pt; //define property_tree object
std::stringstream ss(str_json);
try {
read_json(ss, pt); //parse json
} catch (ptree_error & e) {
return 1;
}

ptree errortype = pt.get_child("");

for (boost::property_tree::ptree::iterator it = errortype.begin(); it != errortype.end(); ++it) {
std::cout << it->first;
std::cout << it->second.get<std::string>("id") << " "
<< it->second.get<std::string>("temperature") << " "
<< it->second.get<std::string>("humidity") << " "
<< std::endl;
}
Sleep(1000);
}
return 0;
}
  • json數據格式
[{"id":115,"chipid":2956442,"date":"2017-03-30 14:06:44","timestamp":1490854004,"temperature":25,"humidity":40.9},
{"id":113,"chipid":2928629,"date":"2017-03-30 14:06:38","timestamp":1490853998,"temperature":24.5,"humidity":58.2},
{"id":112,"chipid":2943477,"date":"2017-03-30 14:07:02","timestamp":1490854022,"temperature":25,"humidity":42.6},
{"id":111,"chipid":2974582,"date":"2017-03-30 14:06:40","timestamp":1490854000,"temperature":24.2,"humidity":33.6},
……
]

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com