PDA

View Full Version : Access network using QNetworkaccessmanger doesn’t work on seperate class



dineshkumar
4th February 2011, 07:51
Hi, i have created a c++ header file for network access and i am able access the network when i create instance in main.cpp, but it is not working(only network access like get,post… remains works fine) when i call it on a separate class.

Sync_Network.h


#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QDebug>
#include <QUrl>
class Sync_Network:public QNetworkAccessManager{
Q_OBJECT
public:
Sync_Network(QString url,QObject *parent=0):QNetworkAccessManager(parent),host(url) {
connect(this,SIGNAL(finished(QNetworkReply*)),this ,SLOT(showReply(QNetworkReply*)));
}
virtual ~Sync_Network(){}
bool Sync_Get(const QString path){
get(QNetworkRequest(QUrl(host+""+path)));
return status;
}
bool Sync_Post(QString params,QString path=""){
QByteArray data;
data.append(params);
post(QNetworkRequest(QUrl(host+""+path)),data);
return status;
}
protected slots:
virtual void showReply(QNetworkReply *reply){
if(!reply->error()) qDebug()<<reply->readAll();
else{
status=false;
qDebug()<<reply->errorString();
}
}
private:
bool status;
QString host;
};

tweet.cpp


#include "Sync_Network.h"

Tweet::Tweet(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Tweet)
{
ui->setupUi(this);
Sync_Network s("http://www.capeconsultancy.com");
s.Sync_Get("/aboutus");
s.Sync_Post("<tweet><username>dinesh</username><passowrd>123456</password></tweet>");
}

Please help me. Thanks in advance

helloworld
4th February 2011, 09:09
I think it is because 's' falls out of scope and is destroyed.. change your code to:



{
ui->setupUi(this);
Sync_Network* s = new Sync_Network("http://www.capeconsultancy.com", this);
s->Sync_Get("/aboutus");
s->Sync_Post("<tweet><username>dinesh</username><passowrd>123456</password></tweet>");
}


Edit: That is, it is not synchronous at all, so it's not really a good solution, but it solves the problem of the signal not being emitted.

What you want is probably Sync_Get to wait before returning:



get(QNetworkRequest(QUrl(host+""+path)));
loop.exec();


then in showReply(QNetworkReply *reply), you exit the event loop:



loop.exit();




private:
bool status;
QString host;
QEventLoop loop;


.. then you can create your Sync_Network on the stack without it being destroyed before the reply is received.