Search code examples
c++qtqnetworkaccessmanagerslot

Network reply after program ends


I wrote program which gets source code of web page from url but i have problem, because this code is prints on screen when program is ending and I can't use data which i downloaded. I think that the problem is because program waits for SIGNAL(finished()). Is any way to process downloaded data in my program before ending?

void Get::getCode()
{
    networkManager = new QNetworkAccessManager(this);
    link = "http://example.com/";
    networkManager->get(QNetworkRequest(QUrl(link)));
    connect(networkManager, SIGNAL(finished(QNetworkReply*)), &process, SLOT(replyFinished(QNetworkReply*)));

    //QDesktopServices::openUrl(QUrl(link));
}

...

    void Process::replyFinished(QNetworkReply* pReply)
{
    QString source(pReply->readAll());
    printf("%s\n", source.toStdString().c_str());
}

...

int main(int argc, char *argv[]){

    QApplication a(argc, argv);

    Get get; get.getCode();
    MainWindow window;

    printf("test point\n");

    return a.exec();
    //return 0;}

"test point" is first on screen and later html code.


Solution

  • The network manager runs asynchronous, which means that your main thread continues immediately after calling the get() method.

    You can solve this by setting up an event loop which waits until the download is completed:

      QEventLoop loop;
      connect(networkManager, SIGNAL(finished()), &loop, SLOT(quit()));
      loop.exec(QEventLoop::ExcludeUserInputEvents);
    

    That should give you the expected result.