QNetworkAccessManager
【1】头文件
想要利用QNetworkAccessManager类,必须在pro文件中添加对应库network,如下:
QT += network
如果利用的VS + QT开发环境,请参考随笔《Qt添加QtNetwork库文件》
【2】示例文件
文件1:
1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include <QMainWindow> 5 #include <QtNetWork> 6 7 namespace Ui 8 { 9 class MainWindow; 10 } 11 12 class MainWindow : public QMainWindow 13 { 14 Q_OBJECT 15 16 public: 17 explicit MainWindow(QWidget *parent = 0); 18 ~MainWindow(); 19 20 private: 21 void get(QUrl u); 22 23 private slots: 24 void on_pushButton_clicked(); 25 void finished(); 26 27 private: 28 Ui::MainWindow *ui; 29 30 QUrl m_url; 31 QString m_htmlText; 32 QNetworkReply *m_pReply; 33 QNetworkAccessManager m_manager; 34 }; 35 36 #endif // MAINWINDOW_H
文件2:
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 4 MainWindow::MainWindow(QWidget *parent) : 5 QMainWindow(parent), 6 ui(new Ui::MainWindow), 7 m_pReply(Q_NULLPTR) 8 { 9 ui->setupUi(this); 10 } 11 12 MainWindow::~MainWindow() 13 { 14 delete ui; 15 } 16 17 void MainWindow::get(QUrl u) 18 { 19 m_url = u; 20 21 if (m_pReply != Q_NULLPTR) 22 { // 更改reply指向位置前一定要保证之前的定义了自动delete 23 m_pReply->deleteLater(); 24 } 25 26 QNetworkRequest request; 27 request.setUrl(m_url); 28 m_pReply = m_manager.get(request); 29 qDebug() << "start get"; 30 connect(m_pReply, &QNetworkReply::finished, this, &MainWindow::finished); 31 } 32 33 void MainWindow::finished() 34 { 35 QByteArray bytes = m_pReply->readAll(); 36 37 m_pReply->deleteLater(); 38 m_pReply = Q_NULLPTR; 39 40 const QVariant redirectionTarget = m_pReply->attribute(QNetworkRequest::RedirectionTargetAttribute); 41 if (!redirectionTarget.isNull()) 42 { //如果网址跳转重新请求 43 const QUrl redirectedUrl = m_url.resolved(redirectionTarget.toUrl()); 44 qDebug() << "redirectedUrl:" << redirectedUrl.url(); 45 get(redirectedUrl); 46 return; 47 } 48 49 qDebug() << "finished"; 50 m_htmlText = bytes; 51 qDebug() << "get ready,read size:" << m_htmlText.size(); 52 53 // 写入文件 54 QFile f("result.html"); 55 f.open(QFile::WriteOnly); 56 f.write(bytes); 57 } 58 59 void MainWindow::on_pushButton_clicked() 60 { 61 m_htmlText = ""; 62 get(QUrl("http://www.baidu.com/")); 63 }
返回的结果文件:
在运行目录中查找result.html文件,双击运行,然后与百度首页作对比,可以发现get获取的数据中不包含图片信息。
【3】总结
示例程序很简单,主要应用QNetworkAccessManager类的get接口。
Good Good Study, Day Day Up.
顺序 选择 循环 总结