In the update, in the test exception, during the download process, found that if the direct system disabled the network, will report errors, can be captured. But if third-party software restricts the networking of programs, the problem comes.
The program will always be there waiting, no exceptions, and no Qnetworkaccessmanager::finsh and Qnetworkreply::error and Qnetworkreply::finsh signals are sent.
So the idea is to add a timeout to the download, but qnetworkaccessmanager,qnetworkreply and qnetworkrequest do not have the relevant setting function. In fact, think about it, there is no way to directly provide timeouts, because the download of the file has a lot of small, the network is fast and slow, what is the time-out? only to find a way to add. Because the exception must be found and handled, the problem must be solved.
First say my solution, using qnetworkreply::d ownloadprogress signal to achieve, their own record for a period of time the number of downloaded bytes, with a timer to regular detection, if a period of time, a little extra download is not, then I think the network timeout is abnormal.
Below the code, you can simply use the code to describe the following:
Statement:
01 |
class NetWorkDownload : public QObject |
05 |
explicit NetWorkDownload(QObject *parent = 0); |
10 |
void startDownload( const QString & url); |
13 |
void handleReply(QNetworkReply * rep); //处理下载完成的数据 |
14 |
void handSize(qint64 size, qint64 all); |
17 |
QNetworkAccessManager manger; |
18 |
int fileDownSize, //已经下载的字节数 |
19 |
lastDownSize; //定时器上次下载的字节数 |
Realize:
01 |
NetWorkDownload::NetWorkDownload(QObject *parent) : |
04 |
//这个connect你也可以用QNetworkReply来链接,QNetworkReply::finsh,QNetworkReply::readyReady这些信号。 |
05 |
connect(&manger,&QNetworkAccessManager::finished, this ,&NetWorkDownload::handleReply); |
06 |
connect(& tm ,&QTimer::timeout, this ,&NetWorkDownload::timeOut); |
09 |
void NetWorkDownload::startDownload( const QString & url) |
12 |
req.setUrl(QUrl(url)); |
13 |
auto rep = manger.get(req); |
14 |
connect(rep,&QNetworkReply::downloadProgress, this ,&NetWorkDownload::handSize); |
21 |
void NetWorkDownload::handSize(qint64 size,qint64 /* all*/ ) |
26 |
void NetWorkDownload::handleReply(QNetworkReply *rep) |
33 |
if ( tm .isActive()) //如果还在定时,就停止 |
37 |
void NetWorkDownload::timeOut() |
39 |
if (lastDownSize != fileDownSize) //如果过了30s,一点字节也没有下载过来,认为超时了。 |
40 |
lastDownSize = fileDownSize; |
Http://www.dushibaiyu.com/2014/10/qnetworkaccessmanager-timeout.html
Http://stackoverflow.com/questions/13207493/qnetworkreply-and-qnetworkaccessmanager-timeout-in-http-request
Add timeout reminders for Qnetworkaccessmanager (log the number of bytes downloaded for a period of time, and periodically detect with a timer to determine if the timeout is exceeded)