PDA

View Full Version : QNetworkAdapter::Post working in Main Application but Not from a Library



pp1010
6th May 2013, 08:49
I want to http post a file to a server though a library used by my application. As the post failed (WireShark shows data not sent from Client).

So, I shifted the code to a function in the Main application...and viola it works... (Data received by Server)

What am I missing, QEventLoop? If yes, how to use it. Tried, but am lost..

Here is the code (used in the Main Application):


//loginscreenmain.h
class loginscreenmain : public QMainWindow
{
Q_OBJECT

public:
explicit loginscreenmain(QWidget *parent = 0);
~loginscreenmain();
QNetworkAccessManager* m_pNAM;
QNetworkReply *m_Reply;
QNetworkRequest m_Request;

void SendPacket();

private slots:
void on_pushButton_2_clicked();
void on_pushButton_clicked();
void on_pushButton_2_pressed();
void on_pushButton_pressed();

private:
Ui::loginscreenmain *ui;
};





void loginscreenmain::SendPacket()
{
CRequestGenerator *oReqGen = new CRequestGenerator(); //Mediator class between Google Protobuf classes and Client Code

CMyRequest *oReq = oReqGen->createMyRequest(); //CMyRequest is Google Protobuf generated class

m_pNAM = NULL;
m_pNAM = new QNetworkAccessManager();

int checksize = oReq->ByteSize();

std::string outputstring;
outputstring = oReq->SerializeAsString(); //Google Protobuf API
checksize = outputstring.size();

//An UTF8 encoded QByteArray
QByteArray byteArray(outputstring.c_str(), outputstring.length());
checksize = byteArray.size();

QUrl oUrl = QUrl(QString("http://blahblahblah")); //URI given here...Tested to Work

m_Request.setUrl(oUrl);
m_Request.setRawHeader("function", "PerformAddition" ); //Protobuf Specific

if(m_pNAM)
{
m_Reply = m_pNAM->post(m_Request,byteArray);
}
}


Added after 27 minutes:

Found the solution: QEventLoop was needed to make the post synchronous.



if(m_pNAM)
{
m_pReply = m_pNAM->post(m_pRequest,m_byteArray);
QEventLoop eventLoop;
QObject::connect(m_pReply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
std::cout << "finished" << std::endl; //request finished here
}


Can also refer: http://www.qtcentre.org/threads/35110-Synchronous-HTTP-requests-and-QEventLoop