PDA

View Full Version : posting to an invalid URL using QNetworkAccessManager



sattu
8th January 2014, 14:50
Hi Everyone, I have a simple requirement on my Arm-Linux embedded platform wherein I need to post to a URL and wait for the reply. I achieve that using the following code-


void MyApp::MyApp()
{
m_networkManager = new QNetworkAccessManager(this); // Instance variable
connect(m_networkManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(onRequestCompleted(QNetworkReply *)));
}

void MyApp::getData()
{
QByteArray dataToBePosted;
QNetworkRequest request;
request.setUrl(QUrl("http://www.domain.foo"));
m_networkManager->post(request,dataToBePosted);
}

void MyApp::onRequestCompleted(QNetworkReply *reply)
{
QByteArray data = reply->readAll();
reply->deleteLater();
}


I have 2 doubts regarding usage of QNetworkAccessManager class-
1) What I observed is that if I post to a valid URL I immediately get a response, but if the URL is invalid then it takes some time for the reply to come (sometimes like 40 secs).
Moreover, if the URL is invalid then I observe an increase in memory usage in my application after the following line-

m_networkManager->post(request,dataToBePosted);
I know this sounds very strange but this is what is happening. If the URL exists then everything is fine, but by mistake if I post to an invalid URL then my memory usage immediately shoots up :confused:

2) In Qt Documentation it is mentioned that
One QNetworkAccessManager should be enough for the whole Qt application.
Suppose I use 2 QNetworkAccessManager objects in my application, will that create any issue?

I would be really glad if someone would clarify my doubts.

anda_skoa
8th January 2014, 15:34
You needlessly create a new QNetworkAccessManager on each call to getData()
Moreover, you never delete it. So each call to getData() leaks a QNetworkAccessManager instance.

Since you already have m_networkManager as an instance member, only create one QNAM instance and re-use it.

Regarding 2 QNAM: that is possible and does not create issues. Using one QNAM is usually more efficient since the instance can then do all kinds of tricks to optimize e.g. connects, like re-using sockets, re-using SSL sessions, etc.

See Peter Hartmann's presentation at this year's Qt Developer Days: http://devdays.kdab.com/wp-content/uploads/2013/11/speeding-up-your-Qt-app-with-new-QtNetwork-features.pdf

Cheers,
_

sattu
8th January 2014, 15:40
You needlessly create a new QNetworkAccessManager on each call to getData()
Moreover, you never delete it. So each call to getData() leaks a QNetworkAccessManager instance.
Since you already have m_networkManager as an instance member, only create one QNAM instance and re-use it.
_
Am extremely sorry for the confusion, actually I have only one instance of QNAM running and I keep re-using it. I modified the code to put it here and so did that mistake. Have rectified it, thanks for pointing it out.