Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt QNetworkReply is always empty

Tags:

c++

qt

I want to see the results of a GET request. By my understanding, this code should do it. 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 runs fine. It just doesn't work.

like image 557
Dirk Avatar asked Jul 16 '13 20:07

Dirk


1 Answers

Try modifying your replyFinished 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 are getting a 200 response:

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

If you are getting a 302 response, you are getting a status redirect. You will need to handle it like this:

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'm returning when encountering a status code of 302 since I don't want the rest of the method to execute.

I hope this helps!

like image 120
Cameron Tinker Avatar answered Oct 23 '22 03:10

Cameron Tinker