我想获得一个网页的源(HTML),例如StackOverflow的主页。
这是我目前编写的代码:
QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QString html = response->readAll(); // Source should be stored here
但是什么也没发生!当我试图获得html
字符串的值时,它是空的(")。
那么,该怎么办呢?我使用Qt 5.3.1.
您需要以异步方式对其进行编码。c++ 11和Qt来拯救我们。请记住,lambda函数体稍后将在事件循环中执行。
// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972
#include <QtNetwork>
#include <functional>
void htmlGet(const QUrl &url, const std::function<void(const QString&)> &fun) {
QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager);
QNetworkReply *response = manager->get(QNetworkRequest(QUrl(url)));
QObject::connect(response, &QNetworkReply::finished, [response, fun]{
response->deleteLater();
response->manager()->deleteLater();
if (response->error() != QNetworkReply::NoError) return;
auto const contentType =
response->header(QNetworkRequest::ContentTypeHeader).toString();
static QRegularExpression re("charset=([!-~]+)");
auto const match = re.match(contentType);
if (!match.hasMatch() || 0 != match.captured(1).compare("utf-8", Qt::CaseInsensitive)) {
qWarning() << "Content charsets other than utf-8 are not implemented yet:" << contentType;
return;
}
auto const html = QString::fromUtf8(response->readAll());
fun(html); // do something with the data
}) && manager.take();
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
htmlGet({"http://www.google.com"}, [](const QString &body){ qDebug() << body; qApp->quit(); });
return app.exec();
}
除非你只使用这段代码一次,你应该把QNetworkManager
实例作为你的控制器类的成员,或者在main
,等等
你必须添加QEventLoop
QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop event;
connect(response,SIGNAL(finished()),&event,SLOT(quit()));
event.exec();
QString html = response->readAll(); // Source should be stored here
QNetworkAccessManager
异步工作。您在get()
之后立即调用readAll()
,但此时还没有发出请求。您需要使用文档中所示的QNetworkAccessManager::finished
信号,并将readAll()
移动到与该信号连接的槽位
一个简短的回答,包括c++ 17的基本部分:
const auto manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished,
this, [](auto reply) {
qDebug() << reply->readAll();
});
manager->get(QNetworkRequest({ "https://www.google.com" }));