返回顶部

收藏

QT获取网页内容

更多

QT的网络库QHTTP和QNetworkAccessManager等都是异步获取网页的方式,用起来相当不爽。

自己写了个同步的网页获取程序。望指点。。。

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QtCore>
#include <iostream>
using namespace std ;
class TT : public QObject
{
    Q_OBJECT
public:
    static QString getHtml(QString url)
    {
        QNetworkAccessManager *manager = new QNetworkAccessManager();
        QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(url)));
        QByteArray responseData;
        QEventLoop eventLoop;
        connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
        eventLoop.exec();       //block until finish
        responseData = reply->readAll();
        return QString(responseData);
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString data = TT::getHtml(QString("http://outofmemory.cn );
    cout<<data.toStdString()<<endl;
    return a.exec();
}
//该片段来自于http://outofmemory.cn

标签:c++,网络

收藏

1人收藏

支持

1

反对

0

发表评论