Solved QNetworkAccessManager doesn't work
-
It just doesn't output the finished.
QNetworkAccessManager manager; QNetworkRequest request; request.setUrl(QUrl("http://www.google.com")); auto response = manager.get(request); connect(response, &QNetworkReply::finished, [] () { qDebug() << "Finished"; });
-
Hi @Volebab,
It looks like your QNetworkAccessManager is being destroyed as soon as you create the request (ie as it goes out of scope).
Try:
QNetworkAccessManager * manager = new QNetworkAccessManager(this);
You need to ensure that the manager lives for as long as you want to be using the request you created with it.
Cheers.
-
@Paul-Colby You are right, thank you.
How to ensure that this pointer isn't going to leak? I mean, I want to use it in a class, how to make sure that it's going to be deleted? -
@Paul-Colby You are right, thank you.
You're welcome :)
How to ensure that this pointer isn't going to leak?
There's lots of options, but you'll notice that in the QNetworkAccessManager constructor, I passed in
this
QNetworkAccessManager * manager = new QNetworkAccessManager(this);
Assuming
this
is aQObject
-derived class, then this sets up parent-child relationship such that whenthis
gets destroyed, its destructor will also destroymanager
.Have a read of Object Trees & Ownership - Construction/Destruction Order of QObjects.
Cheers.
-
@Paul-Colby I just noticed that if I try to use an actual slot it doesn't work anymore.
connect(response, &QNetworkReply::finished, this, &MyClass::getResult);
The getResult is never called.
-
@Volebab said:
connect(response, &QNetworkReply::finished, this, &MyClass::getResult);
Looks okay to me.
Can you show us the updated code that sets up the request, as well as the implementation of the getResult function?
-
webservice.hpp:
#ifndef WEBSERVICE_HPP #define WEBSERVICE_HPP #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> class Webservice : public QObject { Q_OBJECT public: explicit Webservice(QObject *parent = 0); virtual void ~Webservice(); public slots: void sendRequest(); private slots: void getResult(); private: QNetworkAccessManager *manager; QNetworkReply *response; }; #endif // WEBSERVICE_HPP
webservice.cpp:
#include "webservice.hpp" Webservice::Webservice(QObject *parent) : QObject(parent) { manager = new QNetworkAccessManager(this); } void Webservice::~Webservice() { manager->deleteLater(); } void Webservice::sendRequest() { QNetworkRequest request; request.setUrl(QUrl("http://httpin.org/headers")); response = manager->get(request); connect(response, &QNetworkReply::finished, this, &Webservice::getResult); } void Webservice::getResult() { qDebug() << "finished"; qDebug() << response->readAll(); response->deleteLater(); }
-
I fixed it, first: The address was incorrect to it would never call finished but error signal, and second: it's not needed to create an instance of QNetworkAccessManager at all, it will work just fine with a stack allocation.