PDA

View Full Version : How to retry network request for specified amount of time



rawfool
19th August 2014, 14:55
I want to do Http Post and retry if in case some error has occured.


HttpEngine::HttpEngine()
{
nwAccMan = new QNetworkAccessManager(this);
connect(nwAccMan, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
QNetworkProxy proxy(QNetworkProxy::HttpProxy, "192.168.1.111", 810, QString("TTR"), QString());
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)
{
QByteArray data = reply->readAll();
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.

anda_skoa
19th August 2014, 16:43
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,
_

rawfool
20th August 2014, 08:45
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 ?


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*)));
QNetworkProxy proxy(QNetworkProxy::HttpProxy, "192.168.1.111", 810, QString("TTR"), QString());
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();
}

QByteArray data = reply->readAll();
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.

anda_skoa
20th August 2014, 09:27
Yes, that looks about right.

Cheers,
_