QNetworkAccessManager and POST return
-
Hello,
networkMgr = new QNetworkAccessManager(this); connect(mpNetworkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinishedValidation(QNetworkReply*))); mpNetworkMgrSend->post(request, datatoSend); void MyClass::onFinishedValidation(QNetworkReply *reply) { QString data = (QString) reply->readAll(); //It's works! }
With this code I below I can't read the response:
QNetworkReply* reply; reply = mpNetworkMgrSend->post(request, datatoSend); QString data = (QString) reply->readAll();
Why the only way to read the response is inside the slot onFinishedValidation?
Exist a way to read the response outside of slot or both?Thank you!
-
QNetworkAccessManager is designed to work with the Qt event loop. It is event driven and it communications with you also by events. The QNetworkReply::finished() or QNetworkAccessManager::finished(QNetworkReply *) slots are not the only place results can be read, you can also connect the QNetworkReply::readReady() signal and get results incrementally as they stream in.
-
@Helson You cannot just read the response right after sending the post. The communication over network takes time. You have to wait until the response arrives and then read it. QNetworkAccessManager::post() just sends the post it does not wait for the response.
-
@jsulm
It's clear for me now.
Can you show me a example of a response outside of a slot?
I need it to check the response and decide the way the code
If I use slot, I need put all my logic inside of a slot.Thank you and sorry for my bad english.
--
Something likereply = mpNetworkMgrSend->post(request, datatoSend);
if(reply = "true"){
...
} else{
...
} -
You get a pointer to a QNetworkReply instance.
Then you connect its readyRead() signal (or finished()) to a slot where you read the response data.
Where is no need to do busy waiting for the reply.
This is from Qt documentation (replace get() with post()):QNetworkRequest request; request.setUrl(QUrl("http://qt-project.org")); request.setRawHeader("User-Agent", "MyOwnBrowser 1.0"); QNetworkReply *reply = manager->get(request); connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotError(QNetworkReply::NetworkError)));
-
If you want to wait for the response for some reason you can call the QNetworkReply::isFinished() periodically. But take care to not to block the event loop, else you most probably will have an endless loop.
-
I'm trying but without success.
QNetworkReply *reply = manager->get(request); connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotError(QNetworkReply::NetworkError))) while(!reply->isFinished()){ QString dataReply = (QString) reply->readAll(); }
I can not get the reply out of the slot...
-
This post is deleted!