PDA

View Full Version : QNetworkAccessManager and multiples requests



hassinoss
26th August 2014, 10:51
Hi all,

I want to connect to a web service so i used QNetworkAccessManager, and it worked and i got the informations i wanted.
The problem is i want to reconnect to the web service every time to get the currents informations, i was thinking to use a thread to do this, but it doesn't work , the slot connecting to the finish of the QNetworkAccessManager is not invoked until the end of the thread.

This is the code i used to connect to the web service one time :


m_url.setUrl("http://time.jsontest.com/");
m_request.setUrl(m_url);
connect(&m_networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onResult(QNetworkReply*)));
m_networkManager.get(m_request);

wysota
26th August 2014, 11:01
So what exactly is the problem? Why can't you call m_networkManager.get(m_request) again?

hassinoss
26th August 2014, 11:23
I did it, i put m_networkManager.get(m_request); into a method run() of QThread , but the problem is the slot onResult(QNetworkReply*) is not invoked.



void Manager::run()
{
while(true)
{
m_networkManager.get(m_request);
sleep(10);
}
}

wysota
26th August 2014, 12:34
Well, obviously the above code won't work because you have an infinite loop here. But why use a thread at all?

hassinoss
26th August 2014, 12:52
as the title says , i want to reconnect again to the web service , how i can do it without thread ?

wysota
26th August 2014, 13:08
#include <QNetworkAccessManager>
#include <QCoreApplication>
#include <QTimer>
#include <QtDebug>

class ServiceConnector : public QObject {
Q_OBJECT
public:
ServiceConnector(const QUrl &url, QObject *parent = 0) : QObject(parent), m_url(url) {
connect(&m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(processResult(QNetworkReply*)));
connect(&m_timer, SIGNAL(timeout()), this, SLOT(nextQuery()));
}
public slots:
void start(int ms = 1000) {
m_timer.start(ms);
}
private slots:
void nextQuery() {
m_manager.get(QNetworkRequest(m_url));
}
void processResult(QNetworkReply *reply) {
qDebug() << reply->readAll();
reply->deleteLater();
}
private:
QNetworkAccessManager m_manager;
QUrl m_url;
QTimer m_timer;
};

#include "main.moc"

int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
ServiceConnector connector("your webservice url");
connector.start(1000);
return app.exec();
}

anda_skoa
26th August 2014, 14:12
You could at least have provided a link to the other thread so Wysota didn't have to re-ask all the same questions again.

You are starting to look like a troll.

Cheers,
_

hassinoss
26th August 2014, 15:43
I'm sorry i didn't mean it, when posting this Thread i saw the other , so i asked because it treat the same topic, i'm sorry again and thanx you two for your help