post get cookiejar ...



  • Good evening,

    There, I'm blocked again. I could use a little help. I'm a little lost.
    My project is to successfully handle cookie post get http methods... with Qt.
    So I managed to connect to a game via the form and via post.I managed to retrieve the PHPSESSID.
    Now I try to send a request via the get() function so I succeeded but the server returns error 403.
    So I wonder what to do. Apparently if I understood correctly this error means that the server has received my request but it does not allow it. I looked it up on the internet and I inferred it was a cookiejar connection. But now I'm lost I'm forced to inherit this class? I can't do otherwise? since it's virtual functions I do what in these functions? Anyway, I'm a little lost. I'll get you but my code if ever.. Thank you very much.

    
    
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        b_ErrorCode(false),
        b_PhpSessid(false)
    {
        this->ui->setupUi(this);
        this->networkManager = new QNetworkAccessManager; //On crée le QNetworkAccessManager qui va traiter les requêtes
        connect(this->ui->demarrerTelechargement, SIGNAL(clicked()), this, SLOT(Login()));
    }
    
    MainWindow::~MainWindow()
    {
        delete this->ui;
        delete this->networkManager;
    }
    
    void MainWindow::ReplyFinished()
    {
        if (this->b_ErrorCode == false)
        {
            QMessageBox::information(this, "Fin de post", "L'envoi de données par POST a été effectué avec succès !");
            QVariant cookieVar = this->reply->header(QNetworkRequest::SetCookieHeader);
    
    
            if (cookieVar.isValid()) {
                QList<QNetworkCookie> cookies = cookieVar.value<QList<QNetworkCookie> >();
                foreach (QNetworkCookie cookie, cookies) {
                    qDebug() << cookie;
                    if (cookie.name() == "PHPSESSID")
                    {
                        this->b_PhpSessid = true;
                        this->ByteArray_phpSessionId = cookie.value();
                    }
                }
            }
            close();
        }
        this->b_ErrorCode = false;
    }
    
    void MainWindow::slotErrorReply(QNetworkReply::NetworkError)
    {
        this->b_ErrorCode = true;
    
        int i_CodeError = this->reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    
        qDebug() << i_CodeError;
        if (i_CodeError >= 500)
            QMessageBox::critical(this, "Erreur", "Ogame server error code : <br /><br /><em>" + reply->errorString() + "</em>");
        else if (i_CodeError != 200)
            QMessageBox::critical(this, "Erreur", "Error Bad Mail or Password <br /><br /> Code de l'erreur : <br /><em>" + reply->errorString() + "</em>");
    }
    
    void MainWindow::GetPhpSessID()
    {
        QUrlQuery postData;
        postData.addQueryItem("kid", "");
        postData.addQueryItem("language", "en");
        postData.addQueryItem("autologin", "false");
        postData.addQueryItem("credentials[email]", "xxxxxx@gmail.com");
        postData.addQueryItem("credentials[password]", "xxxxx");
        QNetworkRequest requete_PhpSessid(QUrl("https://lobby-api.ogame.gameforge.com/users")); //On crée notre requête avec l'url entrée par l'utilisateur
        requete_PhpSessid.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        this->reply = this->networkManager->post(requete_PhpSessid, postData.toString(QUrl::FullyEncoded).toUtf8());
        connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotErrorReply(QNetworkReply::NetworkError)));
        connect(this->reply, SIGNAL(finished()), this, SLOT(ReplyFinished()));
    }
    
    void MainWindow::GetUserAccount()
    {
        QNetworkRequest requete_GetUSer(QUrl("https://lobby-api.ogame.gameforge.com/users/me/accounts")); //On crée notre requête avec l'url entrée par l'utilisateur
        this->reply = this->networkManager->get(requete_GetUSer);
    
    
        connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotErrorReply(QNetworkReply::NetworkError)));
        connect(this->reply, SIGNAL(finished()), this, SLOT(ReplyFinished()));
    }
    
    void MainWindow::Login()
    {
        this->b_ErrorCode = false;
    
        this->GetPhpSessID();
    
        this->GetUserAccount();
    }
    
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QNetworkAccessManager>
    #include <QMainWindow>
    #include <QDebug>
    #include <QNetworkReply>
    #include <QNetworkRequest>
    #include <QtGui>
    #include <QMessageBox>
    #include <QList>
    #include <QMap>
    #include <QUrlQuery>
    #include <QVariant>
    #include <QNetworkCookie>
    #include <QNetworkCookieJar>
    
    
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        /**
         * @brief MainWindow constructeur de la classe
         * @param parent
         */
        explicit MainWindow(QWidget *parent = 0);
    
        /**
         * @brief Destructeur de la classe
         */
        ~MainWindow();
    
    private:
        /**
         * @brief ui variable qui permet d'accèder a l'interface
         */
        Ui::MainWindow *ui;
    
        /**
         * @brief FromData variable contenant la requete pour les données de log (email, mdp)
         */
        QByteArray  FromData;
    
        /**
          * @brief b_errorCode Boléen true = error or false
          */
        bool         b_ErrorCode;
    
        /**
         * @brief b_PhpSessid booléen true = PHPSESSID trouver si false = PHPSESSID non trouver
         */
        bool         b_PhpSessid;
    
        /**
         * @brief reply
         */
        QNetworkReply *reply;
    
        /**
         * @brief networkManager
         */
        QNetworkAccessManager *networkManager;
    
        /**
         * @brief GetPhpSessID
         */
        void        GetPhpSessID();
    
        /**
         * @brief GetUserAccount
         */
        void        GetUserAccount();
    
        /**
         * @brief ByteArray_phpSessionId
         */
        QByteArray  ByteArray_phpSessionId;
    
    
    private slots:
        /**
         * @brief ReplyFinishedPhpSess Slot appelé a la fin d'une requete.
         * @return rien
         */
        void ReplyFinished();
    
        /**
         * @brief slotErrorReply slot appeler quand il y a une erreur (pendant une demande de requete, perte de connexion ou autre..)
         * @param[QNetworkReplay::NetworkError] : Code erreur reçu par le signal
         * @return rien
         */
        void slotErrorReply(QNetworkReply::NetworkError);
    
        /**
         * @brief Login SLot appeler quand on appuis sur le bouton téléchargement
         * @return rien
         */
        void Login();
    };
    
    #endif // MAINWINDOW_H
    
    


  • @El_Professor
    You have received cookie PHPSESSID from the server during GetPhpSessID(), and you have stored it in a variable. From my limited knowledge, the point is that you from now on you must pass that cookie back to the server in every request (GET, POST) you make. That is how the server knows which session you belong to.

    So in your GetUserAccount() you must put that cookie into its header just before this->networkManager->get(requete_GetUSer). In http://doc.qt.io/qt-5/qnetworkrequest.html see something like http://doc.qt.io/qt-5/qnetworkrequest.html#setHeader & QNetworkRequest::SetCookieHeader. I don't know whether NetworkRequest::CookieLoadControlAttribute & QNetworkRequest::CookieSaveControlAttribute are relevant here too. Or look at http://doc.qt.io/qt-5/qnetworkaccessmanager.html#cookieJar & http://doc.qt.io/qt-5/qnetworkaccessmanager.html#setCookieJar. The principle is the same. I think these calls may be the right way to do things. Something like https://stackoverflow.com/questions/43511916/qnetworkcookiejar-segmentation-fault-qt-5-8 (ignore the bit about segfault!) may help give you the approach.



  • Good evening, thank you for your answer. Unfortunately, I still try all day and I still have the same 403 error. I obviously don't understand the principle. I understood well that it was necessary after having recovered then to store the PHPSESSID to return it to the server before each request get or post so that the server can identify us. I'm a little lost between setcookiejar, setcookieheader, setheader...



  • @El_Professor
    All this untested, but I think you just need to try receiving the "cookiejar" from the server responses and sending it back unchanged to the server in all requests. Something like:

    // initially associate a cookie jar with the manager
    manager = new QNetworkAccessManager;
    QNetworkCookieJar *cJar = new QNetworkCookieJar(manager);
    manager->setCookieJar(cJar);
    // from now on the manager includes the cookie jar
    QNetworkReply * reply = manager->post(req, postData);
    

    The cookie jar needs preserving across calls. Check that you receive the PHPSESSID cookie in it from the server in a response, and then that is preserved and passed back to the server on subsequent requests.

    An explanation from http://www.qtcentre.org/threads/45977-sending-cookies-using-qt reads:

    Attach a QNetworkCookieJar to your QNetworkAccessManager, make requests, cookies are stored and returned to the relevant servers automatically. There's nothing else to it. If the first request you make from your Qt program is the login request then you will have the session cookie(s) in your cookie jar and they will be returned with any subsequent request using the same jar.

    I believe that confirms what I am saying and the principle in the code I have written above.



  • Good evening, you have helped me well, I thank you for it.

    I understand how it works now. So I added your lines in my class constructor. Now I have no more mistakes but I still have a little problem I think.

    In my function GetUserAcount() I create my QNetworkRequest() with my URL. Then I do a get and finally I connect the return of my get.
    Here is the code:

    void MainWindow::GetUserAccount()
    {
        QNetworkRequest requete_GetUSer(QUrl("https://lobby-api.ogame.gameforge.com/users/me/accounts"));
        QNetworkReply * reply_test = this->networkManager->get(requete_GetUSer);
        connect(reply_test, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotErrorReply(QNetworkReply::NetworkError)));
        connect(reply_test, SIGNAL(finished()), this, SLOT(ReplyFinished()));
    }
    

    The problem and slots are never called ReplyFinished() for example is never called. So I wonder if what I did really works.

    I receive the PHPSESSID well during the first call to the post() method.


  • Moderators

    @El_Professor Did you check your connect() calls succeeded?
    Is slotErrorReply() called?



  • Apparently n'i sloterrorReply() nor replyfinished() is called.because I put a qDebug() in each slot and nothing is displayed by for the first call when I retrieve the PHPSESSID via the post() method. i show you my entire code :

    
    
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        b_ErrorCode(false),
        b_PhpSessid(false)
    {
        this->ui->setupUi(this);
    
        this->networkManager = new QNetworkAccessManager; //On crée le QNetworkAccessManager qui va traiter les requêtes
        QNetworkCookieJar *cjar = new QNetworkCookieJar(this->networkManager);
        this->networkManager->setCookieJar(cjar);
    
        connect(this->ui->demarrerTelechargement, SIGNAL(clicked()), this, SLOT(Login()));
    }
    
    MainWindow::~MainWindow()
    {
        delete this->ui;
        delete this->networkManager;
    }
    
    void MainWindow::ReplyFinished()
    {
        qDebug() << "ok";
        if (this->b_ErrorCode == false)
        {
            qDebug() << "Fin de post" << "L'envoi de données par POST a été effectué avec succès !";
            QVariant cookieVar = this->reply->header(QNetworkRequest::SetCookieHeader);
    
    
            if (cookieVar.isValid()) {
                QList<QNetworkCookie> cookies = cookieVar.value<QList<QNetworkCookie> >();
                foreach (QNetworkCookie cookie, cookies) {
                    qDebug() << cookie << reply->url();
                    if (cookie.name() == "PHPSESSID")
                    {
                        this->b_PhpSessid = true;
                        this->ByteArray_phpSessionId = cookie.value();
                        this->b_ErrorCode = false;
                        GetUserAccount();
                    }
                }
            }
            close();
        }
        this->b_ErrorCode = false;
    }
    
    void MainWindow::slotErrorReply(QNetworkReply::NetworkError)
    {
        this->b_ErrorCode = true;
    
        int i_CodeError = this->reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    
        qDebug() << i_CodeError;
        if (i_CodeError >= 500)
            QMessageBox::critical(this, "Erreur", "Ogame server error code : <br /><br /><em>" + reply->errorString() + "</em>");
        else if (i_CodeError != 200)
            QMessageBox::critical(this, "Erreur", "Error Bad Mail or Password <br /><br /> Code de l'erreur : <br /><em>" + reply->errorString() + "</em>");
    }
    
    void MainWindow::GetPhpSessID()
    {
        QUrlQuery postData;
        postData.addQueryItem("kid", "");
        postData.addQueryItem("language", "en");
        postData.addQueryItem("autologin", "false");
        postData.addQueryItem("credentials[email]", "jordan02820@gmail.com");
        postData.addQueryItem("credentials[password]", "aqwzsxaze02820");
        QNetworkRequest requete_PhpSessid(QUrl("https://lobby-api.ogame.gameforge.com/users")); //On crée notre requête avec l'url entrée par l'utilisateur
        requete_PhpSessid.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        this->reply = this->networkManager->post(requete_PhpSessid, postData.toString(QUrl::FullyEncoded).toUtf8());
        connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotErrorReply(QNetworkReply::NetworkError)));
        connect(this->reply, SIGNAL(finished()), this, SLOT(ReplyFinished()));
    }
    
    void MainWindow::GetUserAccount()
    {
        QNetworkRequest requete_GetUSer(QUrl("https://lobby-api.ogame.gameforge.com/users/me/accounts")); //On crée notre requête avec l'url entrée par l'utilisateur
    
        this->reply = this->networkManager->get(requete_GetUSer);
    
    
        connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotErrorReply(QNetworkReply::NetworkError)));
        connect(this->reply, SIGNAL(finished()), this, SLOT(ReplyFinished()));
    }
    
    void MainWindow::Login()
    {
        this->b_ErrorCode = false;
    
        this->GetPhpSessID();
    
    }
    
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QNetworkAccessManager>
    #include <QMainWindow>
    #include <QDebug>
    #include <QNetworkReply>
    #include <QNetworkRequest>
    #include <QtGui>
    #include <QMessageBox>
    #include <QList>
    #include <QMap>
    #include <QUrlQuery>
    #include <QVariant>
    #include <QNetworkCookie>
    #include <QNetworkCookieJar>
    
    
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        /**
         * @brief MainWindow constructeur de la classe
         * @param parent
         */
        explicit MainWindow(QWidget *parent = 0);
    
        /**
         * @brief Destructeur de la classe
         */
        ~MainWindow();
    
    private:
        /**
         * @brief ui variable qui permet d'accèder a l'interface
         */
        Ui::MainWindow *ui;
    
        /**
         * @brief FromData variable contenant la requete pour les données de log (email, mdp)
         */
        QByteArray  FromData;
    
        /**
          * @brief b_errorCode Boléen true = error or false
          */
        bool         b_ErrorCode;
    
        /**
         * @brief b_PhpSessid booléen true = PHPSESSID trouver si false = PHPSESSID non trouver
         */
        bool         b_PhpSessid;
    
        /**
         * @brief reply
         */
        QNetworkReply *reply;
    
        /**
         * @brief networkManager
         */
        QNetworkAccessManager *networkManager;
    
        /**
         * @brief GetPhpSessID
         */
        void        GetPhpSessID();
    
        /**
         * @brief GetUserAccount
         */
        void        GetUserAccount();
    
        /**
         * @brief ByteArray_phpSessionId
         */
        QByteArray  ByteArray_phpSessionId;
    
    private slots:
        /**
         * @brief ReplyFinishedPhpSess Slot appelé a la fin d'une requete.
         * @return rien
         */
        void ReplyFinished();
    
        /**
         * @brief slotErrorReply slot appeler quand il y a une erreur (pendant une demande de requete, perte de connexion ou autre..)
         * @param[QNetworkReplay::NetworkError] : Code erreur reçu par le signal
         * @return rien
         */
        void slotErrorReply(QNetworkReply::NetworkError);
    
        /**
         * @brief Login SLot appeler quand on appuis sur le bouton téléchargement
         * @return rien
         */
        void Login();
    };
    
    #endif // MAINWINDOW_H
    
    

    Thanks again for the help.


  • Moderators

    @El_Professor Did you verify that connect() calls succeeded as I suggested?

    qDebug() << connect(reply_test, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotErrorReply(QNetworkReply::NetworkError)));
    qDebug() << connect(reply_test, SIGNAL(finished()), this, SLOT(ReplyFinished()));
    


  • Yes,

    qDebug() << connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotErrorReply(QNetworkReply::NetworkError)));
        qDebug() << connect(this->reply, SIGNAL(finished()), this, SLOT(ReplyFinished()));
    

    this function sends me back:

    true
    true
    


  • Hello,

    up? please.



  • hello, up?...


  • Qt Champions 2017

    hi @El_Professor ,

    i can just recommend using Wireshark for all kind of network debugging.

    You will see all outgoing and incoming packets and can verify their contents.

    as your connect statements return true, the slots should surely be called when data arrives.



  • Thank you for your, what is wireshark?


  • Qt Champions 2017


Log in to reply
 

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