Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

c++ - Qt QNetworkReply is always empty

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

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

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...