Qt QNetworkReply始终为空

时间:2013-07-16 20:41:03

标签: c++ qt

我想看看GET请求的结果。根据我的理解,这段代码应该这样做。我做错了什么?

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.
}

代码编译并运行正常。它只是不起作用。

1 个答案:

答案 0 :(得分:6)

尝试修改answerFinished插槽,如下所示:

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

然后您可以打印statusCode以查看您是否收到200响应:

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

如果您收到302响应,则表示您正在获取状态重定向。你需要像这样处理它:

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

我遇到状态代码302时返回,因为我不希望执行其余的方法。

我希望这有帮助!