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

How to initialize a QNetworkAccessManager properly



  • Hello everyone,
    As a very beginner 'sunday' Qt develloper I would like I have some questions about how to use the QNetworkAccessManager.

    To summarize very briefly I have a very simple API and I would like to create a very simple Qt client.

    As web developper my first idea is to seperate UI management and Http request management.
    So first question: is that a good pratice in Qt?

    Second question: the QNetworkAccessManager documentation says that one network access manager should be use for the entire application. So how should I initialize it ?

    I've tried many ways but none of them worked except this one:
    create a QNetworkAccessManager static variable
    http_service.cpp:

    #include "http_service.h"
    
    static QNetworkAccessManager nam;
    
    // constructor
    
    QJsonDocument httpService::getBlob(QString url)
    {
        QNetworkRequest request(url);
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    
        QNetworkReply *reply = nam.get(request);
    
        while (!reply->isFinished())
        {
            qApp->processEvents();
        }
    
        // processing response and returing it as QJsonDocument
    }
    
    //...other methods to handle other tyeo of request
    

    It work but I have the feeling that it is not very "Qt compliant".

    Thanks for reading.


  • Lifetime Qt Champion

    Hi and welcome to devnet

    Just make it a member variable of the class that will be using it.

    As for your separation of concerns, it's valid for all languages.


  • Lifetime Qt Champion

    Hi and welcome to devnet

    Just make it a member variable of the class that will be using it.

    As for your separation of concerns, it's valid for all languages.



  • Hello SGaist,

    Thank you very much for your answer.

    I was sure I've already tried to make it a member variable of the class and having some error. Not a the compilation but when I tried to launch the app (app was ended forcefully as the messages read).
    I had to make a mistake at the time but I can remmber I've done differently.

    Anyway now it's working, thank you!


Log in to reply