Qt学习笔记网络(一)

时间:2022-08-26 10:51:38

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

新建一个控制台应用程序

看一下QNetworkAccessManager的帮助文档

Qt学习笔记网络(一)

需要添加Qt + =network

Qt学习笔记网络(一)

新建一个类

.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 在读取时,将行结束符转换成 \n;在写入时,将行结束符转换成本地格式,例如 Win32 平台上是 \r\n
QIODevice::Unbuffered 忽略缓存