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

Receiving JSON from GET request in google apis



  • Hello,

    ive a problem with receiving JSON from request.

    Headers:
    jsontest.h

    Sources:
    main.cpp
    jsontest.cpp

    main.cpp below

    #include <QCoreApplication>
    #include "jsontest.h"
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        JsonTest json;
        json.DoSomething();
        return a.exec();
    }
    

    jsontest.h below

    #ifndef JSONTEST_H
    #define JSONTEST_H
    
    #include <QObject>
    #include <QtNetwork>
    #include <QtCore>
    
    class JsonTest : public QObject
    {
        Q_OBJECT
    public:
        explicit JsonTest(QObject *parent = nullptr);
        void DoSomething();
    signals:
    
    public slots:
        void onResult(QNetworkReply *);
    };
    
    #endif // JSONTEST_H
    
    
    
    

    jsontest.cpp below

    #include "jsontest.h"
    
    JsonTest::JsonTest(QObject *parent) : QObject(parent)
    {
    }
    
    void JsonTest::DoSomething()
    {
        QNetworkAccessManager networkManager;
        connect(&networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onResult(QNetworkReply*)));
        QUrl url("https://www.googleapis.com/customsearch/v1?key=myapihere&cx=017576662512468239146:omuauf_lfve&q=lectures");
        QNetworkRequest request;
        request.setUrl(url);
    
        QNetworkReply* currentReply = networkManager.get(request);  // GET
        qDebug() << currentReply->readAll();
        currentReply->deleteLater();
    }
    
    void JsonTest::onResult(QNetworkReply *reply)
    {
        qDebug() << "lol";
    }
    

    when i copy and paste url in web browser: https://www.googleapis.com/customsearch/v1?key=myapihere&cx=017576662512468239146:omuauf_lfve&q=lectures i will see results but in app the slot does not even execute


  • Lifetime Qt Champion

    Hi and welcome to the forums .
    Its a classic.
    void JsonTest::DoSomething()
    {
    QNetworkAccessManager networkManager; <<< local variable. it will be deleted before getting any reply.

    put it as a member of JsonTest class so it stays alive.



  • This post is deleted!


  • 0_1544477311971_aaa.png

    still the same



  • ok i commented line currentReply->deleteLater(); and it works :D


  • Lifetime Qt Champion

    Hi,

    You are trying to read the reply too early as well as deleting it too early. You should do both in the slot connected to the finished signal.


Log in to reply