Search code examples
qtqnetworkaccessmanagerqnetworkrequestqnetworkreply

QNetworkAccessManager proper usage


I want to POST some info to a php and GET the result from that php. My POST should look like: www.sample.com/test.php?un=user&pass=123345 I am trying all variants with no success:

m_NetworkAccessMNGR = new QNetworkAccessManager(this);
connect(m_NetworkAccessMNGR, SIGNAL(finished(QNetworkReply*)),
        this,SLOT(slotFinishRequest(QNetworkReply*)));
QNetworkRequest networkRequest;
networkRequest.setUrl(QUrl("http://www.sample.com/test.php?un=user&pass=123345"));

QNetworkReply *reply = m_NetworkAccessMNGR->get(networkRequest);

connect(reply, SIGNAL(readyRead()),
        this, SLOT(slotReadyRead()));
connect(reply, SIGNAL(finished()),
        this, SLOT(slotOnRequestCompleted()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
        this, SLOT(slotOnRequestError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
         this, SLOT(slotSslErrors(QList<QSslError>)));

The code doesn't execute any of these slots.
Does anybody has any ideea on what is the problem?
Thank you


Solution

  • Do you have an event loop somewhere else in your code?

    If not, try this :

    QEventLoop loop;
    
    m_NetworkAccessMNGR = new QNetworkAccessManager(this);
    QNetworkRequest networkRequest;
    networkRequest.setUrl(QUrl("http://www.sample.com/test.php?un=user&pass=123345"));
    
    QNetworkReply *reply = m_NetworkAccessMNGR->get(networkRequest);
    
    connect(reply, SIGNAL(readyRead()),
            this, SLOT(slotReadyRead()));
    connect(reply, SIGNAL(finished()),
            this, SLOT(slotOnRequestCompleted()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(slotOnRequestError(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(slotSslErrors(QList<QSslError>)));
    
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    

    Does that work any better?