当我执行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();
}
在何处以及如何设置请求的某种超时?
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();
}
检查一下:
https://doc.qt.io/qt-5/qnetworkrequest.html#settransfertimeout
void qnetworkrequest :: setTransfertimeout(int timeout =DefaultTransferTimeOutConstant)将超时设置为转移超时以毫秒。
如果未在超时之前传输字节,则将中止转移到期。零表示未设置计时器。如果没有提供任何论点,超时是qnetworkRequest :: DefaultTransferTimeOutConstant。如果这函数未调用,超时是禁用的,并且具有值零。
此功能是在QT 5.15中引入的。