Search code examples
c++11httpsopensslpoco-libraries

How to reuse session for Poco::Net::HTTPSClientSession


I have declared a static member variable of class Input_output_class()

Session::Ptr c_pSecureSession=nullptr;

For every request GET/PUT/DELETE/HEAD, I have to create an object of the class Input_output_class(). In the member function of the class I am creating a session as follows Function Get()

{
if(c_pSecureSession)
{
    s_sess = HTTPSClientSession(host, port, pContext, c_pSecureSession); 
}
else
{
   s_sess = HTTPSClientSession(host, port, pContext);
}
 //pContext is a defaultClientContext from singleton Poco::Net::SSLManager 

s_sess->sendRequest(request);
c_pSecureSession = s_sess->sslSession();
cout <<" c_pSecureSession " << c_pSecureSession <<endl;

//Handle response below

 }

SSL MANAGER Singleton init code ——————

{
Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> ptrHandler = new Poco::Net::AcceptCertificateHandler(false);
Poco::Net::Context::Ptr ptrContext = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "");
ptrContext->enableSessionCache(true);
Poco::Net::SSLManager::instance().initializeClient(0, ptrHandler, ptrContext);

}

What I am seeing that session is not being reused and I am getting a new c_pSecureSession pointer for every request.

Could you please help me how to make use of session cacheing ..

Thanks.


Solution

  • First, the basics - the c_pSecureSession is a Poco::AutoPtr, so will be a different instance every time. However, the underlying bare pointer will always be the same - that's the idea behind the smart pointer paradigm - many smart pointers wrap one "naked" pointer.

    It is not clear from the code you posted how are you "reusing" a nullptr Session - in order to do that, you'd have to create a Session manually before (but how, when you have no socket yet?), or first create a HTTPSClientSession and then get it out from there for the subsequent ones (doable).

    But, let's make it simple - you don't need the c_pSecureSession and you don't need to recreate session for every request - create it only once:

    s_sess = HTTPSClientSession(host, port, pContext);
    

    Since you already have the caching enabled for context, the underlying session in s_sess will be reused, just send/receive from it.

    Note that, in order to cache sessions, caching must be enabled on the server side as well and sessions may also have expiration time - if the underlying session expires, a new one will be recreated automatically.

    See testCachedSession for an example on how to deal with sessions.