如何使用 POCO 库连接到 api.github.com

How to connect to api.github.com using POCO library

我正在尝试通过 POCO 库与 github 服务器建立连接,我的代码:

Poco::Net::initializeSSL();

    Poco::Net::Context context(Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");

    URI uri("https://api.github.com/zen");
    std::string path(uri.getPathAndQuery());

    HTTPSClientSession client(uri.getHost(), uri.getPort(), &context);

    HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);

    if (!client.connected())
    {
        int a{ 0 };//<<==ALWAYS END UP HERE, MEANING THAT client isn't connected
    }  

有谁知道如何连接到该服务器,即需要哪些步骤才能实现?

未连接,因为您没有发送请求。尝试:

client.sendRequest(req);

更新:GitHub API requires the user agent header,否则你会得到 403。因此,这是一个功能齐全的示例(在这种特殊情况下,证书处理程序和根证书是可选的,但是很高兴拥有):

#include "Poco/StreamCopier.h"
#include "Poco/URI.h"
#include "Poco/Exception.h"
#include "Poco/SharedPtr.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Net/KeyConsoleHandler.h"
#include "Poco/Net/ConsoleCertificateHandler.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include <memory>
#include <iostream>

using namespace Poco;
using namespace Poco::Net;

class SSLInitializer {
public:
    SSLInitializer() { Poco::Net::initializeSSL(); }

    ~SSLInitializer() { Poco::Net::uninitializeSSL(); }
};

int main(int argc, char** argv)
{
    SSLInitializer sslInitializer;

    SharedPtr<InvalidCertificateHandler> ptrCert = new ConsoleCertificateHandler(false);
    Context::Ptr ptrContext = new Context(Context::CLIENT_USE, "", "", "rootcert.pem", Context::VERIFY_STRICT, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
    SSLManager::instance().initializeClient(0, ptrCert, ptrContext);

    try
    {
        URI uri("https://api.github.com/zen");
        HTTPSClientSession s(uri.getHost(), uri.getPort());
        HTTPRequest request(HTTPRequest::HTTP_GET, uri.getPath());
        request.set("user-agent", "Poco HTTPSClientSession");
        s.sendRequest(request);
        HTTPResponse response;
        std::istream& rs = s.receiveResponse(response);
        StreamCopier::copyStream(rs, std::cout);
        std::cout << std::endl;
    }
    catch (Exception& ex)
    {
        std::cout << ex.displayText() << std::endl;
        return 1;
    }

    return 0;
}

这里是它的执行:

$ gitget
Avoid administrative distraction.