Qt QNetworkReply 始终为空

时间:2023-01-22
本文介绍了Qt QNetworkReply 始终为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想查看 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 始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:在 Qt QML 中为许多文本元素指定字体 下一篇:在 Qt C++ 中使用 OpenSSL

相关文章

最新文章