How to retry network request for specified amount of time
I want to do Http Post and retry if in case some error has occured.
Code:
HttpEngine::HttpEngine()
{
nwAccMan = new QNetworkAccessManager(this);
connect(nwAccMan, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
nwAccMan->setProxy(proxy);
nwAccMan
->post
(QNetworkRequest
(QUrl("https://something.com/fll/browseFolder?")),
QByteArray("uid=test2_sdaee169&pwd=pass&p=%2f%2f"));
}
void HttpEngine::replyFinished(QNetworkReply * reply)
{
qDebug() << data;
}
In the above code, if in case the reply has some error, I need to try to resend request till a timer timeout with interval of 5 seconds. How can I achieve this ?
Thank you.
Re: How to retry network request for specified amount of time
Create a QTimer and connect it to a slot.
On the first try of the request you start it. If it its slot gets called you cancel the current request and abort. If replyFinished() reports success you stop the timer.
Cheers,
_
Re: How to retry network request for specified amount of time
Thank you anda_skoa.
I did like this, found it working fine. But just wanted to check with you, if I'm doing it the correct way.
And in replyFinished() slot, I am posting the network request again, if theres is any error and also if the timer is still active. Is it correct ?
Code:
HttpEngine::HttpEngine()
{
timer.setInterval(25000);
connect(&timer, SIGNAL(timeout()), &timer, SLOT(stop()));
nwAccMan = new QNetworkAccessManager(this);
connect(nwAccMan, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
nwAccMan->setProxy(proxy);
nwAccMan
->post
(QNetworkRequest
(QUrl("https://something.com/fll/browseFolder?")),
QByteArray("uid=test2_sdaee169&pwd=pass&p=%2f%2f"));
timer.start();
}
void HttpEngine::replyFinished(QNetworkReply * reply)
{
qDebug() << "Inside replyFinished()";
if(reply->error() == QNetworkReply::NoError)
{
if(timer.isActive())
{
qDebug() << "Timer is active";
timer.stop();
}
qDebug() << data;
}
else
{
if(timer.isActive())
{
qDebug() << "Timer is active";
qDebug() << "Error: " << reply->errorString();
nwAccMan
->post
(QNetworkRequest
(QUrl("https://something.com/fll/browseFolder?")),
QByteArray("uid=test2_sdaee169&pwd=pass&p=%2f%2f"));
}
}
}
Thank you.
Re: How to retry network request for specified amount of time
Yes, that looks about right.
Cheers,
_