Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
434 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...