Since Qt still does not support to set timeouts on QNetworkRequest
objects, I wrote this little wrapper class:
/**
Usage:
new QReplyTimeout(yourReply, msec);
When the timeout is reached the given reply is closed if still running
*/
class QReplyTimeout : public QObject {
Q_OBJECT
public:
QReplyTimeout(QNetworkReply* reply, const int timeout) : QObject(reply) {
Q_ASSERT(reply);
if (reply) {
QTimer::singleShot(timeout, this, SLOT(timeout()));
}
}
private slots:
void timeout() {
QNetworkReply* reply = static_cast<QNetworkReply*>(parent());
if (reply->isRunning()) {
reply->close();
}
}
};
You can use it in a very simple fire-and-forget manner:
QNetworkAccessManager networkAccessManger;
QNetworkReply* reply = networkAccessManger.get(QNetworkRequest(QUrl("https://www.google.com")));
new QReplyTimeout(r, 100);
If the call to Google does not finish in 100ms, it is aborted. And since the QReplyTimeout
class is parented to the QNetworkReply
, it will be destroyed automatically.
Review the code for any pitfalls, memory leaks, invalid casts and if it's generally in a good style.