gpt4 book ai didi

c++ - 当尝试使用 Qt QNetworkAccessManager 获取网页时,它总是返回 ""

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:19:56 25 4
gpt4 key购买 nike

我正在尝试使用 Qt 获取网页并将其打印在屏幕上。问题是它总是打印“”。它不会进入完成的 SLOT。不知道是不是connect()有问题。代码编译没有错误。尝试不使用事件循环。

代码如下:

网络.h

#ifndef NET_H
#define NET_H

#include <QObject>
#include <QtNetwork>
#include <QString>
#include <QDebug>

class net : public QObject
{
Q_OBJECT
public:
explicit net(QObject *parent = 0);
void get_site(QString url);
QString data;

signals:

public slots:
void err(QNetworkReply *);
void done(QNetworkReply *);

private:

};

#endif // NET_H

net.cpp:

#include "net.h"

net::net(QObject *parent) :
QObject(parent)
{
}

void net::get_site(QString url) {
QNetworkAccessManager man;
QNetworkRequest request;

request.setUrl (QUrl(url));

connect (&man , SIGNAL(finished(QNetworkReply*)) ,this, SLOT(done(QNetworkReply*)));
connect (&man , SIGNAL(finished(QNetworkReply*)) ,this, SLOT(err(QNetworkReply *)));

man.get (QNetworkRequest(QUrl(url)));
}

void net::done(QNetworkReply * reply) {
data = QString(reply->readAll ());
}

void net::err(QNetworkReply * reply) {
data = QString(reply->errorString ());
}

和main.cpp:

#include <QCoreApplication>
#include "net.h"


int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

net netobj;
netobj.get_site("http://stackoverflow.com");
qDebug() << netobj.data;
return a.exec();
}

最佳答案

您的代码中存在一些重大问题。首先,您应该将 QNetworkAccessManager 作为 .h 文件中的类成员:

class net : public QObject
{
...
private:
QNetworkAccessManager nam;
};

此外,您不应将 finished 信号连接到两个不同的插槽。您的 get_site 函数应该是这样的:

void net::get_site(QString url) {

QNetworkRequest request;
request.setUrl (QUrl(url));

connect (&man , SIGNAL(finished(QNetworkReply*)) ,this, SLOT(done(QNetworkReply*)));

man.get (QNetworkRequest(QUrl(url)));
}

您应该按以下方式管理返回的回复:

void net::done(QNetworkReply * reply) {


if (reply->error() == QNetworkReply::NoError)
{
data = QString(reply->readAll ());
}
else
{
data = QString(reply->errorString ());
}
}

关于c++ - 当尝试使用 Qt QNetworkAccessManager 获取网页时,它总是返回 "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com