zoukankan      html  css  js  c++  java
  • Qt学习笔记网络(一)

    Qt5 移除了QHttp是因为功能重复 用QNetworkAccessManager完全能搞定

    新建一个控制台应用程序

    看一下QNetworkAccessManager的帮助文档

    需要添加Qt + =network

    新建一个类

    .h文件

    #ifndef DOWNPAGES_H
    #define DOWNPAGES_H
    #include<QNetworkAccessManager>
    #include <QObject>
    
    class DownPages : public QObject
    {
        Q_OBJECT
    public:
        explicit DownPages(QObject *parent = 0);
        void Do_Download();
    signals:
    
    public slots:
    void replyFinished(QNetworkReply*);
    private :
        QNetworkAccessManager *manager;
    };
    
    #endif // DOWNPAGES_H

    我们声明了一个 QNetworkAccesManager

    在.cpp里我们把它初始化并把它的finshed信号关联槽

    并判断状态是如果 是200也就是请求正常状态把页面输出 

    .cpp文件

    #include "downpages.h"
    #include <QNetworkRequest>
    #include<QNetworkReply>
    #include<QDebug>
    #include<QTextCodec>
    DownPages::DownPages(QObject *parent) :
        QObject(parent)
    {
        manager = new QNetworkAccessManager(this);
        connect(manager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(replyFinished(QNetworkReply*)));
    
        QUrl url;
        //url.setUrl("http://www.cnblogs.com/a/b");
        //url.setUrl("http://www.baidu.com/");
        url.setUrl("http://www.sibaieteco.com/");
        //url.setUrl("www.abaibduc.com");
        QNetworkRequest request(url);
    
        manager->get(request);
    }
    
    void DownPages::Do_Download()
    {
    
    }
    /*
     * 请求完成
     *
     *
     */
    void DownPages::replyFinished(QNetworkReply * reply)
    {
        //查看是否有错误
        switch(reply->error())
        {
        //如果没有错误把页面输出
        case QNetworkReply::NoError:
            qDebug()<<"no error";
    
        {
            QTextCodec * cod=QTextCodec::codecForName("utf-8");
            QString str=cod->toUnicode(reply->readAll());
            qDebug()<<str;
        }
            break;
        case QNetworkReply::ContentNotFoundError:
        {
            QUrl failedUrl;
            failedUrl = reply->request().url();
            int httpStatus = reply->attribute(
                        QNetworkRequest::HttpStatusCodeAttribute).toInt();
            QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
            qDebug()<<"url"<<failedUrl <<httpStatus<<"   "<<reason;
        }
            break;
        default:
        {
            qDebug()<<"Have error"<<reply->errorString()<<" error "<<reply->error();
        }
        }
        qDebug()<<"finished";
    }

    再在这个基础上添加一个下载功能

    .h文件

    #ifndef DOWNPAGES_H
    #define DOWNPAGES_H
    #include<QNetworkAccessManager>
    #include <QObject>
    #include <QFile>
    class QNetworkReply;
    
    class DownPages : public QObject
    {
        Q_OBJECT
    public:
        explicit DownPages(QObject *parent = 0);
        void Do_Download();
    signals:
    
    public slots:
    void replyFinished(QNetworkReply*);
    void readyRead();
    void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
    void downFinished();
    private :
        QNetworkAccessManager *manager;
        QNetworkReply * managerReply;
        QFile *file;
    
    };
    
    #endif // DOWNPAGES_H

    .cpp文件

    主要是添加 了这三个信号

    managerReply  = manager->get(request);
        connect(managerReply,SIGNAL(readyRead()),this,SLOT(readyRead()));
        connect(managerReply,SIGNAL(downloadProgress(qint64,qint64)),
                this,SLOT(downloadProgress(qint64,qint64)));
        connect(managerReply,SIGNAL(finished()),this,SLOT(downFinished()));

    readyRead()开始下载数据

    DownloadProgress显示下载的进度

    还有一个finished

    #include "downpages.h"
    #include <QNetworkRequest>
    #include<QNetworkReply>
    #include<QDebug>
    #include<QTextCodec>
    #include<QFileInfo>
    #include<QDir>
    DownPages::DownPages(QObject *parent) :
        QObject(parent)
    {
        manager = new QNetworkAccessManager(this);
        connect(manager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(replyFinished(QNetworkReply*)));
    
        QUrl url;
        //url.setUrl("http://www.cnblogs.com/a/b");
        //url.setUrl("http://www.baidu.com/");
        //url.setUrl("http://www.sibaieteco.com/");
        url.setUrl("http://files.cnblogs.com/li-peng/WPFMultLanguageDemo.rar");
        QNetworkRequest request(url);
    
        managerReply  = manager->get(request);
        connect(managerReply,SIGNAL(readyRead()),this,SLOT(readyRead()));
        connect(managerReply,SIGNAL(downloadProgress(qint64,qint64)),
                this,SLOT(downloadProgress(qint64,qint64)));
        connect(managerReply,SIGNAL(finished()),this,SLOT(downFinished()));
    }
    
    void DownPages::Do_Download()
    {
    
    }
    
    void DownPages::replyFinished(QNetworkReply * reply)
    {
    
        switch(reply->error())
        {
    
        case QNetworkReply::NoError:
            qDebug()<<"no error";
    
        {
            QTextCodec * cod=QTextCodec::codecForName("utf-8");
            QString str=cod->toUnicode(reply->readAll());
            //qDebug()<<str;
        }
            break;
        case QNetworkReply::ContentNotFoundError:
        {
            QUrl failedUrl;
            failedUrl = reply->request().url();
            int httpStatus = reply->attribute(
                        QNetworkRequest::HttpStatusCodeAttribute).toInt();
            QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
            qDebug()<<"url"<<failedUrl <<httpStatus<<"   "<<reason;
        }
            break;
        default:
        {
            qDebug()<<"Have error"<<reply->errorString()<<" error "<<reply->error();
        }
        }
        qDebug()<<"finished";
    }
    
    void DownPages::readyRead()
    {
        QFileInfo fileinfo(managerReply->url().path());
        QString thefileName = fileinfo.fileName().isEmpty()?"index.html":fileinfo.fileName();
    
        QString thePath ="E:/Test/Down/";
        //qDebug()<<thePath;
        QDir createfile;
        bool exist = createfile.exists(thePath);
        if(!exist)
        {
            createfile.mkpath(thePath);
        }
        thePath +=thefileName;
        file=new QFile(thePath);
    
    //    if(file->open(QIODevice::Append))
    //    {
    //        file->write(managerReply->readAll());
    //        file->flush();
    //        file->close();
    //    }
        if(file->open(QIODevice::Append ))
        {
            file->write(managerReply->readAll());
            qDebug()<<"flu";
            file->flush();
        }
        //delete file;
    }
    
    void DownPages::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
    {
        qDebug()<<"Total:  "<<bytesTotal<<"  current received : "<<bytesReceived;
    }
    
    void DownPages::downFinished()
    {
        file->flush();
        file->close();
        delete file;
    }
    file->open(QIODevice::Append)
    枚举值 描述
    QIODevice::NotOpen 未打开
    QIODevice::ReadOnly 以只读方式打开
    QIODevice::WriteOnly 以只写方式打开
    QIODevice::ReadWrite 以读写方式打开
    QIODevice::Append 以追加的方式打开,新增加的内容将被追加到文件末尾
    QIODevice::Truncate 以重写的方式打开,在写入新的数据时会将原有数据全部清除,游标设置在文件开头。
    QIODevice::Text 在读取时,将行结束符转换成 ;在写入时,将行结束符转换成本地格式,例如 Win32 平台上是
    QIODevice::Unbuffered 忽略缓存
  • 相关阅读:
    我的大厂面试经历(附100+面试题干货)
    大厂面试题:集群部署时的分布式 session 如何实现?
    【转载】Android数据库(SqlLite)操作和db文件查看
    【转载】android ListView详解
    C#根据经纬度获取物理地址
    C#计算两个经纬度的距离
    EXT编写日志文件
    动态数组
    System.Windows.Forms.Timer和System.Timers.Timer的区别 [转]
    SQL Prompt 3 优秀的SQL查询工具 收藏
  • 原文地址:https://www.cnblogs.com/li-peng/p/3656613.html
Copyright © 2011-2022 走看看