PDA

View Full Version : QNetworkReply error handling



timmu
23rd August 2009, 18:11
I'd like to access a website using QNetworkReply and then extract the error from it. I'm most interested in seeing if the website was found or not. The below code always gives "Unknown Error" even when the website is perfectly fine. Has anyone done this before. I'm most thankful for your help.



QNetworkAccessManager* manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
QNetworkReply* reply = manager->get(QNetworkRequest(QUrl("http://www.unknownhost123.com")));
QString err = reply->errorString();//this err will be reported

wysota
25th August 2009, 08:38
Does the actual code look exactly like you posted it here? QNetworkAccessManager works in an asynchronous way so the result is not yet ready when you call errorString() on the reply.

timmu
25th August 2009, 08:52
Thanks Wysota!!
For a very long time I've been spinning my wheels without having any idea what's going on. Now it seems that asynchronous is the keyword for me. However, I have to admit I don't know how to use this knowledge. I've been leraning from here http://doc.trolltech.com/4.4/qnetworkaccessmanager.html
and I get things to work for one request but all falls apart when I have a while loop and try to do multiple queries. Would someone be able to do me a huge favor and perhaps show how this code could be changed to accept multiple requests.

Here's my code:


for(int y=1; y<10; y++)
{

QNetworkAccessManager* nam = new QNetworkAccessManager(this);
QNetworkReply* reply;
fscanf(namefeed, "%s", &sona);
urlstring=QString::fromLocal8Bit(sona, strlen(sona)); url.setUrl(urlstring);
QObject::connect(nam, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
reply = nam->get(QNetworkRequest(url)); url.clear();
}




void MyClass::replyFinished(QNetworkReply* reply)
{
QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute );
if (statusCodeV.toInt()==200){
//do something
}
else{
// do something else
}

delete reply;
}

wysota
25th August 2009, 08:54
You can use QEventLoop to turn the asynchronous mechanism into synchronous, if you want. An example of doing that is in the Keeping the GUI Responsive article.

timmu
25th August 2009, 08:58
This is a great idea! But would it work with my code above? Where would the QEventLoop go? I've been playing with other timing tricks but nothing so far. Also this didn't do it:


QCoreApplication::processEvents();

wysota
25th August 2009, 09:07
Just read the article...