Qt QNetworkReply总是空的 [英] Qt QNetworkReply is always empty
问题描述
我想查看GET请求的结果。根据我的理解,这段代码应该做。我做错了什么?
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.
推荐答案
尝试修改您的replyFinished广告位,如下所示:
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();
然后,您可以打印statusCode以查看是否收到200响应:
You can then print the statusCode to see if you are getting a 200 response:
qDebug() << QVariant(statusCode).toString();
如果您得到302响应,您将获得状态重定向。您将需要这样处理:
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;
}
我遇到状态代码302时返回,想要其余的方法执行。
I'm returning when encountering a status code of 302 since I don't want the rest of the method to execute.
我希望这有助于!
这篇关于Qt QNetworkReply总是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!