Reputation: 21
I have a class (RequestHandler) that I call from my main Application class to call various web services. Once a service has completed the class sends a Signal back to the calling class to say that it has finished(possibly with QString message). I have the Signal working in a test method but the QNetworkAccessManager is not working at all. I am quite new to QT and C++. Thanks for your help.
// RequestHandler.h
#ifndef REQUESTHANDLER_H_
#define REQUESTHANDLER_H_
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QOBJECT>
#include "MainAppClass.hpp"
class RequestHandler : public QObject
{
Q_OBJECT
public:
explicit RequestHandler(QObject *parent = 0);
void validateRegistration(QString reg);
void onStatusUpdateCompleted();
void sayHi();
signals:
void sendSignal(QString txt);
private:
QNetworkAccessManager* manager;
QObject* thisObj;
public slots:
void onRequestCompleted();
};
#endif /* REQUESTHANDLER_H_ */
RequestHandler.cpp
#include "RequestHandler.h"
RequestHandler::RequestHandler(QObject *parent) : QObject(parent)
{
thisObj= parent;
}
void RequestHandler::validateRegistration(QString reg) {
QNetworkRequest request;
request.setUrl(QUrl("the_registration_url"));
manager = new QNetworkAccessManager();
QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(finished()), this, SLOT(onRequestCompleted()));
}
void RequestHandler::onRequestCompleted() {
// not getting here at all
}
void RequestHandler::sayHi()
{
// this is working
QObject::connect(this, SIGNAL(sendSignal(QString)), thisCellCast, SLOT(recieveValue(QString)));
emit sendSignal("HERES THE SIGNAL");
}
I am calling this class like this:
// test slots and reg
RequestHandler rh(this);
//working
rh.sayHi();
// not working
rh.validateRegistration("test");
Thanks for your help.
Upvotes: 2
Views: 2558
Reputation: 6339
You typically should be using QNetworkAccessManager
by connecting to error()
and
finished()
signals, so that you will be notified on error occurred.
This is really bad idea to construct QNetworkAccessManager
object in validateRegistration()
as it will cause memory leak and you need only one object of such
kind. So do it in RequestHandler
's constructor.
void RequestHandler::validateRegistration(QString reg)
{
QUrl url("the_registration_url");
QNetworkRequest request(url);
QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(finished()), SLOT(onRequestCompleted()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
SLOT(onError(QNetworkReply::NetworkError)));
}
void RequestHandler::onRequestCompleted()
{
qDebug() << "Request succeeded";
}
void RequestHandler::onError(QNetworkReply::NetworkError code)
{
qError() << "Request failed with code " << code;
}
And also make sure you have QApplication::exec() called somewhere, so you have the main event loop running.
Upvotes: 1