Search code examples
c++qthttprequest

How to send http request synchronously in QT?


The following code uses QT's Network API to send HTTP request and get the response:

void AnotherHttpClient::finished(QNetworkReply *qNetworkReply)
{
    qDebug() << qNetworkReply->readAll();
}

void AnotherHttpClient::get(QString url)
{
    QNetworkAccessManager *man = new QNetworkAccessManager(this);
    connect(man, &QNetworkAccessManager::finished, this, finished);
    const QUrl qurl = QUrl(url);
    QNetworkRequest request(qurl);
    man->get(request);
}

I need to make this code synchronous and I need get method to return the qNetworkReply. How should I do this? BTW are there any other synchronous way to send Http request in QT?


Solution

  • You can do as following:

    QNetworkAccessManager l_nm;
    QUrl l_url ("http://foo.bar");
    QNetworkRequest l_req(l_url);
    QNetworkReply *l_reply = l_nm.get(l_req);
    QEventLoop l_event_loop;
    QObject::connect(l_reply, SIGNAL(finished()), &l_event_loop, SLOT(quit()));
    l_event_loop.exec();
    

    but using an event loop inside a Qt application is the worst idea ever.