使用libCurl和JsonCpp从https webserver解析 [英] Using libCurl and JsonCpp to parse from https webserver
问题描述
所以我一直在互联网上查找一个使用libcurl和jsoncpp解析JSON的基本示例,但我还没有找到一个。
有人请给我正确的方向或在这里指定,一个简单的例子使用libcurl和jsoncpp,从指定的网页下载json(链接本身以.json结尾,所以它将直接拉json)解析和打印。 / p>
感谢您的帮助。非常感谢!
Euden
a)HTTP GET一个JSON对象通过libcurl然后b)解析它与JsonCpp。 @WhozCraig是正确的说,这是两个完全独立的活动,但我碰巧有一个项目,这两个所以我聚合这个小样本,从 如果你把这段代码放在一个名为
main.cpp
g ++ main.cpp -ljsoncpp -lcurl -o example.out&& ./example.out
// main.cpp
#include< cstdint> ;
#include< iostream>
#include< memory>
#include< string>
#include< curl / curl.h>
#include< json / json.h>
namespace
{
std :: size_t callback(
const char * in,
std :: size_t size,
std :: size_t num,
std :: string * out)
{
const std :: size_t totalBytes(size * num);
out-> append(in,totalBytes);
return totalBytes;
}
}
int main()
{
const std :: string url(http://date.jsontest.com/ );
CURL * curl = curl_easy_init();
//设置远程URL。
curl_easy_setopt(curl,CURLOPT_URL,url.c_str());
//不要打扰尝试IPv6,这将增加DNS解析时间。
curl_easy_setopt(curl,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
//不要永远等待,10秒后超时。
curl_easy_setopt(curl,CURLOPT_TIMEOUT,10);
//如有必要,请遵循HTTP重定向。
curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1L);
//响应信息。
int httpCode(0);
std :: unique_ptr< std :: string> httpData(new std :: string());
//连接数据处理函数。
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,callback);
//连接数据容器(将作为最后一个参数传递给
//回调处理函数)。可以是任何指针类型,因为它将
//内部作为void指针传递。
curl_easy_setopt(curl,CURLOPT_WRITEDATA,httpData.get());
//运行我们的HTTP GET命令,捕获HTTP响应代码,并清理。
curl_easy_perform(curl);
curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,& httpCode);
curl_easy_cleanup(curl);
if(httpCode == 200)
{
std :: cout< \\\
Got successful response from<< url<< std :: endl;
//响应看起来不错 - 现在使用Curl完成。尝试解析结果
//并打印出来。
Json :: Value jsonData;
Json :: Reader jsonReader;
if(jsonReader.parse(* httpData,jsonData))
{
std :: cout< 成功解析JSON数据< std :: endl;
std :: cout<< \\\
JSON data received:< std :: endl;
std :: cout<< jsonData.toStyledString()<< std :: endl;
const std :: string dateString(jsonData [date]。asString());
const std :: size_t unixTimeMs(
jsonData [milliseconds_since_epoch]。asUInt64());
const std :: string timeString(jsonData [time]。asString());
std :: cout<< Natively parsed:< std :: endl;
std :: cout<< \tDate string:<< dateString<< std :: endl;
std :: cout<< \tUnix timeMs:< unixTimeMs<< std :: endl;
std :: cout<< \tTime string:<< timeString<< std :: endl;
std :: cout<< std :: endl;
}
else
{
std :: cout< 无法将HTTP数据解析为JSON<< std :: endl;
std :: cout<< HTTP data was:\\\
<< * httpData.get()< std :: endl;
return 1;
}
}
else
{
std :: cout< Could not GET from<< url<< - exiting< std :: endl;
return 1;
}
return 0;
}
输出如下:
从http://date.jsontest.com/成功响应
成功解析JSON数据
收到的JSON数据:
{
date:03-09-2015,
milliseconds_since_epoch:1425938476314,
time:10:01:16 PM
}
原生解析:
日期字符串:03-09-2015
Unix timeMs:1425938476314
时间字符串:10:01:16 PM
So I've been looking around the internet for a basic example of parsing JSON using libcurl and jsoncpp but I've not been able to find one.
Could someone please point me in the right direction or specify here, a simple example of using libcurl and jsoncpp, downloading json from a specified webpage (the link itself ending in .json so it will be pulling json directly) parsing it and printing it.
All help is appreciated. Thanks!
Euden
Here's a self-contained example to a) HTTP GET a JSON object via libcurl and then b) parse it with JsonCpp. @WhozCraig is correct to say that these are two totally separate activities, but I happen to have a project that does both so I aggregated this small sample that fetches and parses the JSON from this nifty page.
If you put this code in a file called main.cpp
, then you can compile, link, and run (assuming libcurl and libjsoncpp are available on your path) with:
g++ main.cpp -ljsoncpp -lcurl -o example.out && ./example.out
// main.cpp
#include <cstdint>
#include <iostream>
#include <memory>
#include <string>
#include <curl/curl.h>
#include <json/json.h>
namespace
{
std::size_t callback(
const char* in,
std::size_t size,
std::size_t num,
std::string* out)
{
const std::size_t totalBytes(size * num);
out->append(in, totalBytes);
return totalBytes;
}
}
int main()
{
const std::string url("http://date.jsontest.com/");
CURL* curl = curl_easy_init();
// Set remote URL.
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
// Don't bother trying IPv6, which would increase DNS resolution time.
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
// Don't wait forever, time out after 10 seconds.
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
// Follow HTTP redirects if necessary.
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
// Response information.
int httpCode(0);
std::unique_ptr<std::string> httpData(new std::string());
// Hook up data handling function.
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
// Hook up data container (will be passed as the last parameter to the
// callback handling function). Can be any pointer type, since it will
// internally be passed as a void pointer.
curl_easy_setopt(curl, CURLOPT_WRITEDATA, httpData.get());
// Run our HTTP GET command, capture the HTTP response code, and clean up.
curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
curl_easy_cleanup(curl);
if (httpCode == 200)
{
std::cout << "\nGot successful response from " << url << std::endl;
// Response looks good - done using Curl now. Try to parse the results
// and print them out.
Json::Value jsonData;
Json::Reader jsonReader;
if (jsonReader.parse(*httpData, jsonData))
{
std::cout << "Successfully parsed JSON data" << std::endl;
std::cout << "\nJSON data received:" << std::endl;
std::cout << jsonData.toStyledString() << std::endl;
const std::string dateString(jsonData["date"].asString());
const std::size_t unixTimeMs(
jsonData["milliseconds_since_epoch"].asUInt64());
const std::string timeString(jsonData["time"].asString());
std::cout << "Natively parsed:" << std::endl;
std::cout << "\tDate string: " << dateString << std::endl;
std::cout << "\tUnix timeMs: " << unixTimeMs << std::endl;
std::cout << "\tTime string: " << timeString << std::endl;
std::cout << std::endl;
}
else
{
std::cout << "Could not parse HTTP data as JSON" << std::endl;
std::cout << "HTTP data was:\n" << *httpData.get() << std::endl;
return 1;
}
}
else
{
std::cout << "Couldn't GET from " << url << " - exiting" << std::endl;
return 1;
}
return 0;
}
Output looks like:
Got successful response from http://date.jsontest.com/ Successfully parsed JSON data JSON data received: { "date" : "03-09-2015", "milliseconds_since_epoch" : 1425938476314, "time" : "10:01:16 PM" } Natively parsed: Date string: 03-09-2015 Unix timeMs: 1425938476314 Time string: 10:01:16 PM
这篇关于使用libCurl和JsonCpp从https webserver解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!