Qt QNetworkReply is always empty

I want to see the results of a GET request. In my opinion, this code should do this. What am I doing wrong?

void getDoc::on_pushButton_2_clicked() { manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); manager->get(QNetworkRequest(QUrl("http://www.google.com"))); } void getDoc::replyFinished(QNetworkReply *reply) { qDebug() << reply->error(); //prints 0. So it worked. Yay! QByteArray data=reply->readAll(); qDebug() << data; // This is blank / empty QString str(data); qDebug() << "Contents of the reply: "; qDebug() << str; //this is blank or does not print. } 

The code compiles and works fine. It just doesn't work.

+7
c ++ qt
source share
1 answer

Try changing your answerFinished slot to look like this:

 QByteArray bytes = reply->readAll(); QString str = QString::fromUtf8(bytes.data(), bytes.size()); int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); 

You can then print the statusCode to see if you get a 200 response:

 qDebug() << QVariant(statusCode).toString(); 

If you get a 302 response, you get a status redirect. You will need to handle it as follows:

 if(statusCode == 302) { QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); qDebug() << "redirected from " + replyUrl + " to " + newUrl.toString(); QNetworkRequest newRequest(newUrl); manager->get(newRequest); return; } 

I return when I encounter a status code of 302, since I do not want the rest of the method to be executed.

Hope this helps!

+4
source share

All Articles