解决QNetworkAccessManager 请求返回UnknownNetworkError,无法继续请求问题

前提:

       使用QNetworkAccessManager 进行post请求, 如果在请求期间网络断开,网络恢复后,依然会提示请求失败,返回UnknownNetworkError。

问题解决:

QNetworkAccessManager 有一个函数

networkAccessible : NetworkAccessibility


This property holds whether the network is currently accessible via this network access manager.

If the network is not accessible the network access manager will not process any new network requests, all such requests will fail with an error. Requests with URLs with the file:// scheme will still be processed.

By default the value of this property reflects the physical state of the device. Applications may override it to disable all network requests via this network access manager by calling

e文不好的小伙伴,翻译一下看看,大体意思请求网络失败后,会保存当前的网络状态, 导致后面继续请求也是失败。

根据文档

Network requests can be reenabled again by calling

networkAccessManager->setNetworkAccessible(QNetworkAccessManager::Accessible);

要恢复网络请求调用一setNetworkAccessible即可。

只需要在QNetworkAccessManager执行get或者post的时候,获取一下NetworkAccessible的状态, 再设置一下就好了

void QPayHeartBeat::post()
{
    if(m_NetManager){;
        QNetworkRequest request = setRequest();
        QByteArray data = setReplyData();
        //判断一下网络状态, 如果为NotAccessible 重新设置一下
        if(m_NetManager->networkAccessible() == QNetworkAccessManager::NotAccessible){
            m_NetManager->setNetworkAccessible(QNetworkAccessManager::Accessible);
        }
        QNetworkReply *reply = m_NetManager->post(request, data);
        //这里是我自定义的超时类, 无需理会
        QReplyTimeOut *pTimeout = new QReplyTimeOut(reply, 1000 * 5);
        connect(pTimeout, &QReplyTimeOut::timeout, this, [&]{
            qDebug() << "time out";
        });
        connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));

    }
}

困扰一个多月的问题, 终于解决了。。。果然有问题, 还得多看下文档。有相同问题的小伙伴可以参考一下。

你可能感兴趣的:(QT之路)