[SOLVED]How would I send http requests correctly?



  • Not long ago I wrote a server using Qt. In general it works fairly well, having the ability to store sessions, log you in, etc.

    When I use a web browser and I log in then a session containing my name is created, and if I try to enter again I will get recognised and the server will display my name saying that I do not need to login again until this session expires.

    So I decided to further extend the server by also writing a client that can connect to it and get back a reply. If I try to connect again with the client I should get the already logged in message. The thing though is that this is not what happening. Each new request I make with the client results in a new session being created, as if it is a completely different person.

    What I do from inside the client is

       QString siteurl = QString("http://localhost:8080");
        QUrl url(QString(siteurl+"/login/"));
    
        // create custom temporary event loop on stack
        QEventLoop eventLoop;
    
        QUrlQuery postData;
    
        postData.addQueryItem("action", "login");
        postData.addQueryItem("username", "name");
        postData.addQueryItem("pass", "pass");
    
        QNetworkAccessManager mgr;
        QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    
        // the HTTP request
        QNetworkRequest req(url);
        req.setHeader(QNetworkRequest::ContentTypeHeader,
            "application/x-www-form-urlencoded");
    
        QNetworkReply *reply = mgr.post(req, postData.toString(QUrl::FullyEncoded).toUtf8());
    
        eventLoop.exec();
    
        if (reply->error() == QNetworkReply::NoError)
        {
    
            qDebug() << "OK";
    
            delete reply;
        }
        else
        {
            qDebug() << "Failed: " << reply->errorString();
    
            delete reply;
        }
    

    How can I correctly write my client so as to be able to use the session that I currently obtained after logging in once?


  • Moderators

    Each time you create a new instance of QNetworkAccessManager so it has no knowledge of previous sessions.
    Either keep and reuse the same instance or at least share the cookie jar (if the session is stored in a cookie).



  • Got it, thanks for the answer. You are correct that is how sessions are saved. Allow me to test this later and get back at you, enough programming for one day .

    EDIT
    It indeed works correctly now.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.