qt4 http

Qt网络(二)HTTP编程


HTTP即超文本传输协议,它是一种文件传输协议。这一节中我们将讲解如何利用HTTP从网站上下载文件。


下载网页:
[cpp]  view plain  copy
  1. private:  
  2.     QNetworkAccessManager *manager;  
  3. private slots:  
  4.     void replyFinished(QNetworkReply *);  

[cpp]  view plain  copy
  1. Widget::Widget(QWidget *parent) :  
  2.     QWidget(parent),  
  3.     ui(new Ui::Widget)  
  4. {  
  5.     ui->setupUi(this);  
  6.     manager = new QNetworkAccessManager(this);  //新建QNetworkAccessManager对象  
  7.     connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));  
  8.     manager->get(QNetworkRequest(QUrl("http://www.yafeilinux.com"))); //发送请求  
  9.   
  10. }  
  11.   
  12.   
  13. void Widget::replyFinished(QNetworkReply *reply)  //当回复结束后  
  14. {  
  15.   
  16.     QTextCodec *codec = QTextCodec::codecForName("utf8");  
  17.     QString all = codec->toUnicode(reply->readAll());  
  18.    // ui->textBrowser->setText(all);  
  19.     ui->textBrowser->setHtml(all);  
  20.     reply->deleteLater();   //最后要释放reply对象  
  21. }  
1.manager = new QNetworkAccessManager(this);  //新建QNetworkAccessManager对象
 2.使用get发送请求连接
manager->get(QNetworkRequest(QUrl("http://www.yafeilinux.com"))); //发送请求
3.在请求完成时,manager会发出信号SIGNAL(finished(QNetworkReply*)),这时执行槽函数replyFinished,将下载到的数据显示出来,以html方式
 ui->textBrowser->setHtml(all);


下载文件
[cpp]  view plain  copy
  1. //widget.h  
  2. #ifndef WIDGET_H  
  3. #define WIDGET_H  
  4. #include <QtNetwork>  
  5. #include <QWidget>  
  6.   
  7. namespace Ui {  
  8.     class Widget;  
  9. }  
  10.   
  11. class Widget : public QWidget  
  12. {  
  13.     Q_OBJECT  
  14. public:  
  15.     explicit Widget(QWidget *parent = 0);  
  16.     ~Widget();  
  17.         void startRequest(QUrl url); //请求链接  
  18. protected:  
  19.     //void changeEvent(QEvent *e);  
  20. private:  
  21.     Ui::Widget *ui;  
  22.     QNetworkAccessManager *manager;  
  23.     QNetworkReply *reply;  
  24.      QUrl url;   //存储网络地址  
  25.      QFile *file;  //文件指针  
  26. private slots:  
  27.     //void replyFinished(QNetworkReply *);  
  28.     void on_pushButton_clicked();  
  29.     void httpFinished();  //完成下载后的处理  
  30.     void httpReadyRead();  //接收到数据时的处理  
  31.     void updateDataReadProgress(qint64,qint64); //更新进度条  
  32. };  
  33.   
  34. #endif // WIDGET_H  

[cpp]  view plain  copy
  1. //widget.cpp  
  2. #include "widget.h"  
  3. #include "ui_widget.h"  
  4.   
  5. Widget::Widget(QWidget *parent) :  
  6.     QWidget(parent),  
  7.     ui(new Ui::Widget)  
  8. {  
  9.     ui->setupUi(this);  
  10.   
  11.     manager = new QNetworkAccessManager(this);  //新建QNetworkAccessManager对象  
  12.    // connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));  
  13.    // manager->get(QNetworkRequest(QUrl("http://www.yafeilinux.com"))); //发送请求  
  14.     ui->progressBar->hide();  
  15. }  
  16.   
  17. Widget::~Widget()  
  18. {  
  19.     delete ui;  
  20. }  
  21. /* 
  22. void Widget::replyFinished(QNetworkReply *reply)  //当回复结束后 
  23. { 
  24.     QTextCodec *codec = QTextCodec::codecForName("utf8"); 
  25.     QString all = codec->toUnicode(reply->readAll()); 
  26.     //ui->textBrowser->setText(all); 
  27.     ui->textBrowser->setHtml(all); 
  28.     reply->deleteLater();   //最后要释放reply对象 
  29. } 
  30. */  
  31.   
  32. void Widget::on_pushButton_clicked()  
  33. {  
  34.   url = ui->lineEdit->text();  
  35.  //获取在界面中输入的url地址,如http://zz.onlinedown.net/down/laolafangkuaijin.rar  
  36.     QFileInfo info(url.path());  
  37.     QString fileName(info.fileName());  
  38.     //获取文件名  
  39.     if (fileName.isEmpty()) fileName = "index.html";  
  40. //如果文件名为空,则使用“index.html”,  
  41. //例如使用“http://www.yafeilinux.com”时,文件名就为空  
  42.     file = new QFile(fileName);  
  43.     if(!file->open(QIODevice::WriteOnly))  
  44.     {   //如果打开文件失败,则删除file,并使file指针为0,然后返回  
  45.         qDebug() << "file open error";  
  46.         delete file;  
  47.         file = 0;  
  48.         return;  
  49.     }  
  50.     startRequest(url);  //进行链接请求  
  51.     ui->progressBar->setValue(0);  //进度条的值设为0  
  52.     ui->progressBar->show();  //显示进度条  
  53. }  
  54.   
  55.   
  56. void Widget::startRequest(QUrl url)  //链接请求  
  57.   
  58. {  
  59.   
  60.     reply = manager->get(QNetworkRequest(url));  
  61.     //下面关联信号和槽  
  62.     connect(reply,SIGNAL(finished()),this,SLOT(httpFinished()));  
  63.     //下载完成后  
  64.     connect(reply,SIGNAL(readyRead()),this,SLOT(httpReadyRead()));  
  65.     //有可用数据时  
  66.     connect(reply,SIGNAL(downloadProgress(qint64,qint64)),  
  67.             this,SLOT(updateDataReadProgress(qint64,qint64)));  
  68.     //更新进度条  
  69. }  
  70.   
  71.   
  72. void Widget::httpReadyRead()   //有可用数据  
  73.   
  74. {  
  75.     if (file) file->write(reply->readAll());  //如果文件存在,则写入文件  
  76. }  
  77.   
  78. void Widget::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)  
  79.  {  
  80.     ui->progressBar->setMaximum(totalBytes); //最大值  
  81.     ui->progressBar->setValue(bytesRead);  //当前值  
  82. }  
  83.   
  84. void Widget::httpFinished()  //完成下载  
  85. {  
  86.     ui->progressBar->hide();  
  87.     file->flush();  
  88.     file->close();  
  89.     reply->deleteLater();  
  90.     reply = 0;  
  91.     delete file;  
  92.     file = 0;  
  93. }  
用到的几个信号
readyRead信号在请求的数据中有新的数据响应的时候产生,什么才算新的数据,一次从外网传输过来一个什么数据包?help没讲---暂时理解刚传过来的某个包属于请求的1部分
finished信号在请求的数据全部返回时产生
downloadProgress信号在..help没讲,可能是定时发生吧

void QHttp::readyRead ( const QHttpResponseHeader & resp ) [signal]

This signal is emitted when there is new response data to read.

If you specified a device in the request where the data should be written to, then this signal is not emitted; instead the data is written directly to the device.

The response header is passed in resp.

You can read the data with the readAll() or read() functions

This signal is useful if you want to process the data in chunks as soon as it becomes available. If you are only interested in the complete data, just connect to the requestFinished() signal and read the data then instead.


void QNetworkReply::downloadProgress ( qint64 bytesReceived, qint64 bytesTotal ) [signal]

This signal is emitted to indicate the progress of the download part of this network request, if there's any. If there's no download associated with this request, this signal will be emitted once with 0 as the value of both bytesReceived and bytesTotal.

The bytesReceived parameter indicates the number of bytes received, while bytesTotal indicates the total number of bytes expected to be downloaded. If the number of bytes to be downloaded is not known, bytesTotal will be -1.

The download is finished when bytesReceived is equal to bytesTotal. At that time, bytesTotal will not be -1.

Note that the values of both bytesReceived and bytesTotal may be different from size(), the total number of bytes obtained through read() or readAll(), or the value of the header(ContentLengthHeader). The reason for that is that there may be protocol overhead or the data may be compressed during the download.


void QNetworkReply::finished () [signal]

This signal is emitted when the reply has finished processing. After this signal is emitted, there will be no more updates to the reply's data or metadata.

Unless close() has been called, the reply will be still be opened for reading, so the data can be retrieved by calls to read() or readAll(). In particular, if no calls to read() were made as a result of readyRead(), a call to readAll() will retrieve the full contents in a QByteArray.

This signal is emitted in tandem with QNetworkAccessManager::finished() where that signal's reply parameter is this object.

Note: Do not delete the object in the slot connected to this signal. Use deleteLater().

You can also use isFinished() to check if a QNetworkReply has finished even before you receive the finished() signal.


1.
manager = new QNetworkAccessManager(this);  //新建QNetworkAccessManager对象
2.
file = new QFile(fileName);//创建文件
reply = manager->get(QNetworkRequest(url));//请求连接
3.
在readyRead信号时,将新的数据写入文件
在downloadProgress信号时,更新进度条
在finished信号时,释放各个资源

可见下载网页和文件都是manager->get来完成的。网页部分是将数据显示在textBrowser,文件部分是将数据存入文件。
并且网页请求可以像下载文件那样每1小部分下载完就显示出来,即在readyRead信号时将收到的部分数据显示出来


下图是wireshark在此次下载网页程序执行时的抓包结果,可以看到http是封装在tcp里面

猜你喜欢

转载自blog.csdn.net/u014746838/article/details/79411139
qt4