How to use OpenSSL in POCO C++ library correctly

北慕城南 提交于 2019-12-02 23:22:28

Let's take Net/samples/httpget as an example, let's copy httpget/ as a new httpsget directory:

  1. open Makefile, add "PocoNetSSL" to target_libs
  2. replace 'HTTPClientSession' with 'HTTPSClientSession'
  3. you need to create Poco::Net::Context for SSL use
  4. replace 'HTTPClientSession session(uri.getHost(), uri.getPort());' with following two lines:
const Context::Ptr context = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
HTTPSClientSession session(uri.getHost(), uri.getPort(), context);

Summary:

  1. add PocoNetSSL as a lib_depends
  2. use Poco::Net::Context with HTTPSClientSession

No, you do not need the Application object. Here's a fully functional example:

$ httpsget https://httpbin.org/user-agent
{
  "user-agent": "Poco HTTPSClientSession"
}

Code:

#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
    {
        if (argc > 1)
        {
            URI uri(argv[1]);
            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);
        }
    }
    catch (Exception& ex)
    {
        std::cout << ex.displayText() << std::endl;
        return 1;
    }

    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!