Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QML XMLHttpRequest and proxy



  • By default, Qt XMLHttpRequest doesn't have any possibility to set network proxy.
    Do we have any alternatives to send network request from QML, using network proxy?



  • Qt version 5.13.2
    QML XMLHttpRequest implement and wrapper as follow

    The QQmlXMLHttpRequest have QNetworkAccessManager type member m_nam, set m_nam code as follow:

     QQmlXMLHttpRequest *r = new QQmlXMLHttpRequest(scope.engine->v8Engine->networkAccessManager(), scope.engine);
    

    You can use the api void QQmlEngine::setNetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory *factory) defined you own QNetworkAccessManager.

    class MyNetworkAccessManager : public QNetworkAccessManager
    {
        Q_OBJECT
    public:
        MyNetworkAccessManager(QObject* parent=nullptr):
            QNetworkAccessManager(parent)
        {}
    
    protected:
        QNetworkReply *createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &originalReq, QIODevice *outgoingData = nullptr) {
    
    #ifdef QT_DEBUG
            qDebug() << Q_FUNC_INFO << "url:" << originalReq.url();
    #endif
            // do something before request
            // set the cookie
            // set proxy
            // ...
            return this->QNetworkAccessManager::createRequest(op, originalReq, outgoingData);
        }
    };
    
    class CacheableNetworkAccessManagerFactory : public QQmlNetworkAccessManagerFactory
    {
    public:
        // use by xmlhttprequest
        // use by qml type such Image
        virtual QNetworkAccessManager *create(QObject *parent) {
             QNetworkAccessManager *nam = new MyNetworkAccessManager(parent);
    
    //        QNetworkAccessManager *nam = new QNetworkAccessManager(parent);
            QNetworkDiskCache* diskCache = new QNetworkDiskCache(nam);
    
            QString cachePath = QStandardPaths::displayName(QStandardPaths::AppDataLocation) + "/image-cache";
    
            diskCache->setCacheDirectory(cachePath);
            diskCache->setMaximumCacheSize(100 * 1024 * 1024);   // 100 MB
    
            nam->setCache(diskCache);
    
    #ifdef QT_DEBUG
            qDebug() << Q_FUNC_INFO << " cachePath:" << diskCache->cacheDirectory();
    #endif
            return nam;
        }
    };
    

    If you want use prue qml to set http proxy, try the 3rdparty library.


Log in to reply