I'm trying to send http requests in QT5 but I can't find a solution
There is a class I use to handle all requests
class ClientCore : public QObject
{
Q_OBJECT
public:
...
QNetworkReply *sendGetRequset(QUrl &url);
...
private:
...
QNetworkAccessManager *manager;
QNetworkRequest request;
QNetworkReply *reply;
};
The function
QNetworkReply *ClientCore::sendGetRequset(QUrl &url)
accepts a reference of a QUrl object as parameter, uses it as the target address and send the request
QEventLoop loop;
QTimer timer;
timer.setInterval(RETRYTIME); // timeout after 8 seconds
timer.setSingleShot(true);
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
request.setUrl(url);
int total = 1; //try at most three times if failed
while (total <= 3) {
reply = manager->get(request);
total++;
timer.start();
loop.exec();
if (timer.isActive() && reply->error() == QNetworkReply::NoError) {
return reply;
} else {
reply->abort();
timer.stop();
}
}
return nullptr;
I wonder that is there any hidden asynchronous danger which means the variable "reply" may be refreshed before returned?
For example, if I have serval pushbuttons on the UI layer, and each of them uses this function like below
QNetworkReply *reply = clientCore->sentGetRequset(url);
if (reply != nullptr){
//much to do
}
In addition, is there any way I can improve these codes?
Comments
Post a Comment