QT获取网页上的信息(json格式)

在.pro文件中添加

QT += network
#ifndef MYHTML_H
#define MYHTML_H

#include 
#include 
#include 
#include 
#include "QtCore"
#include "qtimer.h"

class MyHtml : public QWidget
{
    Q_OBJECT
public:
    explicit MyHtml(QWidget *parent = 0);
    QString getHtml(QString url);
    void eventloopQuit();
signals:
    void finished(QString);
    void ReadTimeOut();
public slots:

private:
    QNetworkAccessManager *manager;
    QNetworkReply *reply;
    QTimer *htmlreadtimer;

private slots:
    void slot_replayFinished(QNetworkReply *);
    void HtmlReadTimerOut();
};

#endif // MYHTML_H
#include "myhtml.h"

MyHtml::MyHtml(QWidget *parent) :
    QWidget(parent)
{

}

QString MyHtml::getHtml(QString url)
{
    manager = new QNetworkAccessManager();
    htmlreadtimer = new QTimer(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(slot_replayFinished(QNetworkReply*)));
    connect(htmlreadtimer,SIGNAL(timeout()),this,SLOT(HtmlReadTimerOut()));
    htmlreadtimer->start(5000);
    reply = manager->get(QNetworkRequest(QUrl(url)));
    return QString();
}

void MyHtml::slot_replayFinished(QNetworkReply *reply)
{
    htmlreadtimer->stop();
    QString responseData;
    responseData = reply->readAll();
    reply->deleteLater();//最后要释放replay对象

    emit finished(responseData);
}

void MyHtml::eventloopQuit()
{
    htmlreadtimer->stop();
    reply->deleteLater();//最后要释放replay对象
    manager->deleteLater();
}

void MyHtml::HtmlReadTimerOut()
{
    eventloopQuit();
    emit ReadTimeOut();
}

 

你可能感兴趣的:(Qt)