Qt QNetworkReply 始终为空

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)