11

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.

1 Answer 1

9

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!

3
  • Thanks. The qDebug() gives a code of 200, so it works. How do I now access the content of the page? And what does QString xml(str) do?
    – Dirk
    Jul 17, 2013 at 15:35
  • 1
    Great to hear that it works! I copied the above code from another project of mine and forgot to remove the QString xml(str) line. Thanks for bring that to my attention. The QString str should give you access to the page content. Let me know if it doesn't. Jul 17, 2013 at 18:18
  • 1
    See also QNetworkRequest::FollowRedirectsAttribute (doc.qt.io/qt-5/qnetworkrequest.html), if you use Qt 5.6 < Mar 28, 2017 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.