我想查看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.
}
该代码可以编译并正常运行。就是行不通。
最佳答案
尝试将您的replyFinished插槽修改为如下所示:
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时,我要返回,因为我不希望该方法的其余部分执行。
我希望这有帮助!
关于c++ - Qt QNetworkReply始终为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17686561/