Two requests in the same QNetworkAccessManager
-
I have a class with a QNetworkAccessManager on it and I have two webservices that I have to consult, the first one has a few information and the other has other information, they are all in the same context and that is why i wrapped in a class, the thing is, how to make two requets in the same QNetworkAccessManager and manipulate each webservice separated? For example, the webservice1 returns the user name, so I need to check if it's from the webservice1 get and set the user name in a variable within the class, and if it's from the webservice2 get and set the address of the user in a variable within the class.
-
Hi @Volebab said:
how to make two requets in the same QNetworkAccessManager and manipulate each webservice separated? For example, the webservice1 returns the user name, so I need to check if it's from the webservice1 get and set the user name in a variable within the class, and if it's from the webservice2 get and set the address of the user in a variable within the class.
As is often the case, there's many ways you could do it, but here's just one example (pseudo code only):
class MyClass : QObject { Q_OBJECT public: MyClass(...) : QObject(...) { QNetworkRequest webservice1Request; // @todo setup webservice1Request. QNetworkReply * const reply1 = networkAccessManager->get(webservice1Request); connect(reply1, QNetworkReply::finished, this, MyClass::getUserName); QNetworkRequest webservice2Request; // @todo setup webservice2Request. QNetworkReply * const reply2 = networkAccessManager->get(webservice2Request); connect(reply2, QNetworkReply::finished, this, MyClass::getUserAddress); } private slots: MyClass::getUserName() { QNetworkReply * const reply = qobject_cast<QNetworkReply *>(sender()); Q_CHECK_PTR(reply); userName = reply->readAll(); reply->deleteLater(); } MyClass::getUserAddress() { QNetworkReply * const reply = qobject_cast<QNetworkReply *>(sender()); Q_CHECK_PTR(reply); userAddress = reply->readAll(); reply->deleteLater(); } private: QNetworkAccessManger networkAccessManager; QString userName, userAddress; }
The slots could be simplified by making the
QNetworkReply
instances class member variables if you preferred.Cheers.
-
@Paul-Colby I decided that I will split in two different classes, as the user can choose with one he wants to use, but I liked your way as well, thank you.
-
@Paul-Colby said:
The slots could be simplified by making the QNetworkReply instances class member variables if you preferred.
Or by remapping the
finished()
signal to pass theQNetworkReply
as parameter (thus not requiring usage ofsender()
).