Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
QT附带的例子比较好:
class HttpWindow : public QDialog
{
    Q_OBJECT
public:
    HttpWindow(QWidget 
*parent = 0);

    
void startRequest(QUrl url);
private slots:
    
void downloadFile();
    
void cancelDownload();
    
void httpFinished();
    
void httpReadyRead();
    
void updateDataReadProgress(qint64 bytesRead, qint64 totalBytes);
    
void enableDownloadButton();
    
void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *);
private:
    QLabel 
*statusLabel;
    QLabel 
*urlLabel;
    QLineEdit 
*urlLineEdit;
    QProgressDialog 
*progressDialog;
    QPushButton 
*downloadButton;
    QPushButton 
*quitButton;
    QDialogButtonBox 
*buttonBox;

    QUrl url;
    QNetworkAccessManager qnam;
    QNetworkReply 
*reply;
    QFile 
*file;
    
int httpGetId;
    
bool httpRequestAborted;
};
其中槽有:
1.开始下载
2.取消下载
3.预备下载
4.下载完成
5.进度回调


实现为:
void HttpWindow::startRequest(QUrl url)
{
    reply 
= qnam.get(QNetworkRequest(url));
    connect(reply, SIGNAL(finished()),
            
this, SLOT(httpFinished()));
    connect(reply, SIGNAL(readyRead()),
            
this, SLOT(httpReadyRead()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
            
this, SLOT(updateDataReadProgress(qint64,qint64)));
}
该函数主要针对给定url绑定事件
void HttpWindow::downloadFile()
{
    url 
= urlLineEdit->text();

    QFileInfo fileInfo(url.path());
    QString fileName 
= fileInfo.fileName();
    fileName 
= "downloadfile.dat";
    
if(fileName.isEmpty())
        fileName 
= "index.html";

    
if(QFile::exists(fileName)) {
        
if (QMessageBox::question(this, tr("HTTP"), 
                                  tr(
"There already exists a file called %1 in "
                                     
"the current directory. Overwrite?").arg(fileName),
                                  QMessageBox::Yes
|QMessageBox::No, QMessageBox::No)
            
== QMessageBox::No)
            
return;
        QFile::remove(fileName);
    }

    file 
= new QFile(fileName);
    
if (!file->open(QIODevice::WriteOnly)) {
        QMessageBox::information(
this, tr("HTTP"),
                                 tr(
"Unable to save the file %1: %2.")
                                 .arg(fileName).arg(file
->errorString()));
        delete file;
        file 
= 0;
        
return;
    }

    progressDialog
->setWindowTitle(tr("HTTP"));
    progressDialog
->setLabelText(tr("Downloading %1.").arg(fileName));
    downloadButton
->setEnabled(false);

    
// schedule the request
    httpRequestAborted = false;
    startRequest(url);
}
当点击下载的时候,会执行该函数
获取url链接,生成本地文件,...
void HttpWindow::cancelDownload()
{
    statusLabel
->setText(tr("Download canceled."));
    httpRequestAborted 
= true;
    reply
->abort();
    downloadButton
->setEnabled(true);
}
终止下载,主要函数是reply->abort();
void HttpWindow::httpFinished()
{
    
if (httpRequestAborted) {
        
if (file) {
            file
->close();
            file
->remove();
            delete file;
            file 
= 0;
        }
        reply
->deleteLater();
        progressDialog
->hide();
        
return;
    }

    progressDialog
->hide();
    file
->flush();
    file
->close();


    QVariant redirectionTarget 
= reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    
if (reply->error()) {
        file
->remove();
        QMessageBox::information(
this, tr("HTTP"),
                                 tr(
"Download failed: %1.")
                                 .arg(reply
->errorString()));
        downloadButton
->setEnabled(true);
    } 
else if (!redirectionTarget.isNull()) {        
        QUrl newUrl 
= url.resolved(redirectionTarget.toUrl());
        
if (QMessageBox::question(this, tr("HTTP"),
                                  tr(
"Redirect to %1 ?").arg(newUrl.toString()),
                                  QMessageBox::Yes 
| QMessageBox::No) == QMessageBox::Yes) {
            url 
= newUrl;
            reply
->deleteLater();
            file
->open(QIODevice::WriteOnly);
            file
->resize(0);
            startRequest(url);
            
return;
        }
    } 
else {
        QString fileName 
= QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
        statusLabel
->setText(tr("Downloaded %1 to current directory.").arg(fileName));
        downloadButton
->setEnabled(true);
    }

    reply
->deleteLater();
    reply 
= 0;
    delete file;
    file 
= 0;
}
  下载结束动作
void HttpWindow::httpReadyRead()
{
    
// this slot gets called every time the QNetworkReply has new data.
    
// We read all of its new data and write it into the file.
    
// That way we use less RAM than when reading it at the finished()
    
// signal of the QNetworkReply
    if (file)
        file
->write(reply->readAll());
}
写文件回调
void HttpWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
    
if (httpRequestAborted)
        
return;

    progressDialog
->setMaximum(totalBytes);
    progressDialog
->setValue(bytesRead);
}
进度回调

要点:
1.针对QNetReply绑定需要的信号和槽
2.实现需要的槽函数

posted on 2011-11-16 20:23 ccsdu2009 阅读(12999) 评论(2)  编辑 收藏 引用 所属分类: QT编程
Comments
  • # re: QT学习笔记-29.使用QT HTTP下载网络文件
    22
    Posted @ 2015-09-29 10:56
    这段代码怎么设置文件下载保存的路经呢?  回复  更多评论   
  • # re: QT学习笔记-29.使用QT HTTP下载网络文件
    ccsdu2009
    Posted @ 2015-10-08 08:37
    @22
    downloadFile()函数  回复  更多评论   

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理