我想查看 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.
尝试将您的回复已完成槽修改为如下所示:
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 始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!