使用libCurl和JsonCpp从https Web服务器解析

z31licg0  于 2022-12-01  发布在  其他
关注(0)|答案(2)|浏览(115)

因此,我一直在互联网上寻找使用libcurl和jsoncpp解析JSON的基本示例,但我一直无法找到。
有人能给我指出正确的方向吗?或者在这里指定一个简单的例子,使用libcurl和jsoncpp,从指定的网页下载json(链接本身以.json结尾,所以它将直接拉json),解析并打印它。
感谢所有帮助。谢谢!
尤登

vs3odd8k

vs3odd8k1#

下面是一个自包含的示例:a)通过libcurl HTTP GET JSON对象,然后b)使用JsonCpp解析它。@WhozCraig说这是两个完全独立的活动是正确的,但我碰巧有一个项目同时执行这两个活动,所以我聚合了这个从this nifty page获取和解析JSON的小示例。
如果将这段代码放在一个名为main.cpp的文件中,那么就可以编译、链接和运行(假设libcurl和libjsoncpp在您的路径中可用):
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;
}

输出如下所示:

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
ru9i0ody

ru9i0ody2#

@ConnorManning上面提供的代码在2022年仍然运行良好(我不能在那里发表评论,因为我没有足够的“点”来做到这一点)
但是,编译后它可能在urlSIGSEGV,所以这里是快速修复。

const std::string url("http://date.jsontest.com/");

进入

const char* url = "http://date.jsontest.com/";

以同样的方式编译,它应该能很好地工作。

相关问题