14

执行 http 请求时如何设置超时?

我有这个代码:

{
    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();
}

我在哪里以及如何为请求设置某种超时?

4

2 回答 2

26
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();
}
于 2012-11-05T10:11:55.707 回答
0

看一下这个:

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

void QNetworkRequest::setTransferTimeout(int timeout = DefaultTransferTimeoutConstant) 将超时设置为以毫秒为单位的传输超时。

如果在超时到期之前没有传输任何字节,则传输被中止。零表示没有设置定时器。如果未提供参数,则超时为 QNetworkRequest::DefaultTransferTimeoutConstant。如果未调用此函数,则超时被禁用并且值为 0。

这个函数是在 Qt 5.15 中引入的。

于 2022-01-15T04:58:03.030 回答