QNetworkReply and QNetworkAccessManager timeout in http request
Asked Answered
S

2

15

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?

Striped answered 3/11, 2012 at 8:40 Comment(1)
I am using m_networkManager->setTransferTimeout(30000)Blanco
C
29
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();
}
Clavier answered 5/11, 2012 at 10:11 Comment(5)
Don't forget to delete the reply.Hermineherminia
With download file process, with big file we need timeout bigger? Solution for this case?Degression
@kienbui No. There are separate signals for this, e.g. bytesAvailable or uploadProgressVinic
We can vote "add builtin support for network timeouts" at here: bugreports.qt.io/browse/QTBUG-3443Degression
this is a brilliant solution @ClavierRotary
S
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.

Snowinsummer answered 15/1, 2022 at 4:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.