PDA

View Full Version : http request without signals and slots



whites11
6th January 2010, 14:54
hi all.
i'm a newbie in qt programmin, so please be patient.
i'm writing a qt library and i need to perform an http request to a remote server and, of course, read the response.
i don't need at all to use the signals and slots system, because i have to wait for the http call to finish before going on with the code.
is there a way to do that? i prefer to use the new network api, if possible

thanks

christian

wysota
6th January 2010, 16:53
Use QNetworkAccessManager together with QEventLoop.

whites11
6th January 2010, 19:51
thanks for the answer.

my "download" method is this (code found on the forum, i think it's posted by you):



QNetworkAccessManager* manager = new QNetworkAccessManager();
QUrl murl = this->url;
QNetworkReply *reply = manager->get(QNetworkRequest(url));
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
QTimer timer;
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); // just in case
timer.start(5000);
loop.exec();
QByteArray result = reply->readAll();

if ( reply->error() != QNetworkReply::NoError ) {
qDebug() << "Request failed:" << reply->errorString();
return;
}

qDebug() << "Reply from the server: ";
qDebug() << result;
}

but when i run it i get:


QEventLoop: Cannot be used without QApplication
QObject::startTimer: QTimer can only be used with threads started with QThread

and the program loops

i'm writing a shared library, so there is not a QApplication. is there another way, then?

wysota
6th January 2010, 20:34
No, you need a Q(Core)Application object. Someone has to create it - either you when initializing your library or the application that uses your library.

whites11
7th January 2010, 11:53
thanks, declaring a QCoreApplication did the trick.
last quetion, is there a way to esatablish if a QCoreApplication exists before creating a new one? in that case i could create a qcoreapplication only if needed

wysota
7th January 2010, 15:15
QCoreApplication is a singleton, you can query for its instance through QCoreApplication::instance().

whites11
7th January 2010, 16:39
well wysota, thanks again
you have a beer payed if you pass here :)