14

How do I setup a timeout when I do an http request?

I have this code:

{
    QNetworkRequest request;

    request.setUrl(QUrl("http://www.foo.com"));
    request.setRawHeader("User-Agent", USER_AGENT.toUtf8());
    request.setRawHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    request.setRawHeader("Accept",
        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.setRawHeader("Accept-Language", "en-us,en;q=0.5");
    request.setRawHeader("Connection", "Keep-Alive");

    reply = m_networkManager->get(request);
    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
}

Where and how do I setup some kind of timeout to the request?

Mat
  • 202,337
  • 40
  • 393
  • 406
user63898
  • 29,839
  • 85
  • 272
  • 514

2 Answers2

27
QTimer timer;    
timer.setSingleShot(true);

QEventLoop loop;
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
timer.start(30000);   // 30 secs. timeout
loop.exec();

if(timer.isActive()) {
    timer.stop();
    if(m_reply->error() > 0) {
      ... // handle error
    }
    else {      
      int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

      if (v >= 200 && v < 300) {  // Success
        ...
      }
    }
} else {
   // timeout
   disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));

   reply->abort();
}
Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52
cyber_raj
  • 1,780
  • 1
  • 14
  • 25
4

check this out:

https://doc.qt.io/qt-5/qnetworkrequest.html#setTransferTimeout

void QNetworkRequest::setTransferTimeout(int timeout = DefaultTransferTimeoutConstant) Sets timeout as the transfer timeout in milliseconds.

Transfers are aborted if no bytes are transferred before the timeout expires. Zero means no timer is set. If no argument is provided, the timeout is QNetworkRequest::DefaultTransferTimeoutConstant. If this function is not called, the timeout is disabled and has the value zero.

This function was introduced in Qt 5.15.

xiaoyifang
  • 919
  • 12
  • 13