遵循QT5.5中的重定向

时间:2018-07-17 13:41:29

标签: c++ qt qt5 qnetworkreply qnetworkrequest

我有一个在Qt 5.6上运行良好的程序

const QUrl qurl(url);
QNetworkRequest request(qurl);
//github redirects the request, so this attribute must be set to true, otherwise returns nothing
//from qt5.6
request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
QNetworkAccessManager manager;
QNetworkReply * reply = manager.get(request);

不幸的是,这仅在Qt 5.6中有效

有人可以帮助我进行重定向吗Qt5.5(Ubuntu 16.04)我想我必须手动遵循重定向,但是我没有找到关于它的教程。

我找到了Qt4的解决方案-> QNetworkReply and 301 redirect

我希望Qt5有更多“更新”。

谢谢

1 个答案:

答案 0 :(得分:0)

这是我按照QNetworkReply and 301 redirect中的Qt4样式解决问题的方法。

如果有人有更好的解决方案,请发布

    QNetworkAccessManager manager;
    QVariant possibleRedirectUrl;
    QNetworkReply * reply;

    QUrl qurl;
    qurl.setUrl(url);

    //we check if there is any redirect to follow it
    //from Qt 5.6 redirects can be automatically followed by setting
    //request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    //here is done automatically becaus of Ubuntu 16.04 Qt version (5.5)

    do{
        qInfo() <<"Downloading " << qurl;

        QNetworkRequest request(qurl);
        reply = manager.get(request);

        qInfo() << "waiting to finish...";

        _timeout=false;
        _timer->start(timeout);

        //if download takes more time that set on timeout cancel download
        while(!_timeout){
            qApp->processEvents();
            if(reply->isFinished()) break;
        }

        _timeout = false;

        qInfo() << "finished!";

        possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        qurl = possibleRedirectUrl.toUrl();
        qInfo() << qurl;

    }while(possibleRedirectUrl.isValid());