feat: QNetworkAccessmanager and QNetworkReply and QNetworkRequest

提供网络协议的7层模型中的 中高层的网络协议:Http/FTP/SNMP等

QNetworkAccessmanager  协调网络操作类(处理网络的请求和回应):负责发送网络请求,创建网络响应
QNetworkRequest        网络请求
QNetworkReply          网络请求的响应(提供finished()/readyRead()/downloadProgress()信号),监测网络响应的执行情况,执行相应的操作
This commit is contained in:
touwoyimuli 2019-12-07 00:05:57 +08:00
parent 76f5be9614
commit 19d8cade29
16 changed files with 422 additions and 2 deletions

108
QtHttpEx/ExHttp.cpp Normal file
View File

@ -0,0 +1,108 @@
#include "ExHttp.h"
#include "ui_ExHttp.h"
#include <QMessageBox>
#include <QDir>
#include <QDesktopServices>
ExHttp::ExHttp(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ExHttp)
{
ui->setupUi(this);
setWindowTitle("QNetworkAccessManager 网络管理使用 Http 协议下载");
m_networkManager = new QNetworkAccessManager(this);
}
ExHttp::~ExHttp()
{
delete ui;
}
//下载文件
void ExHttp::on_btnDown_clicked()
{
QString urlSpec = ui->lineEditUrl->text().trimmed(); //去掉字符串的首尾的空格
if (urlSpec.isEmpty()) {
QMessageBox::information(this, "提示", "下载地址URL为NULL");
return;
}
QUrl url = QUrl::fromUserInput(urlSpec);
if (!url.isValid()) {
QMessageBox::information(this, "提示", QString("无效URL: %1 \n 错误信息: %2").arg(urlSpec, url.errorString()));
return;
}
QString dir = ui->lineEditFile->text().trimmed();
if (dir.isEmpty()) {
QMessageBox::information(this, "提示", "保存地址为空");
return;
}
QString fileFileName = dir + url.fileName(); //文件保存地址 + 文件名
if (QFile::exists(fileFileName))
QFile::remove(fileFileName);
m_file = new QFile(fileFileName); //创建临时文件
if (!m_file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, "提示", "打开临时文件错误");
return;
}
ui->btnDown->setEnabled(false);
m_reply = m_networkManager->get(QNetworkRequest(url)); //发送get网络请求创建网络响应
connect(m_reply, SIGNAL(finished()), this, SLOT(onFinished()));
connect(m_reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(m_reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(onDownloadProgress(qint64,qint64)));
}
//默认的保存路径
void ExHttp::on_btnFile_clicked()
{
QString currPath = QDir::currentPath();
QDir dir(currPath);
dir.mkdir("temp");
ui->lineEditFile->setText(currPath + "/temp/");
}
//网络响应结束
void ExHttp::onFinished()
{
QFileInfo fileInfo;
fileInfo.setFile(m_file->fileName());
m_file->close();
delete m_file;
m_file = nullptr;
m_reply->deleteLater();
m_reply = nullptr;
if (ui->checkBox->isChecked()) //勾选了,下载完成之后,打开下载的文件 //absoluteFilePath() 返回包含文件名的绝对路径。
QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absoluteFilePath())); //使用默认软件的打开下载的文件
ui->btnDown->setEnabled(true);
}
//读取下载的数据
void ExHttp::onReadyRead()
{
m_file->write(m_reply->readAll()); //将返回的数据进行读取,写入到临时文件中
}
//下载进程
void ExHttp::onDownloadProgress(qint64 bytesRea, qint64 totalBytes)
{
ui->progressBar->setMaximum(totalBytes);
ui->progressBar->setValue(bytesRea);
}
void ExHttp::on_lineEditUrl_textChanged(const QString &arg1)
{
ui->progressBar->setMaximum(100);
ui->progressBar->setValue(0);
}

View File

@ -0,0 +1,109 @@
#include "ExHttp.h"
#include "ui_ExHttp.h"
#include <QMessageBox>
#include <QDir>
#include <QDesktopServices>
ExHttp::ExHttp(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ExHttp)
{
ui->setupUi(this);
setWindowTitle("QNetworkAccessManager 网络管理使用 Http 协议下载");
m_networkManager = new QNetworkAccessManager(this);
m_reply = nullptr;
m_file = nullptr;
}
ExHttp::~ExHttp()
{
delete ui;
}
//下载文件
void ExHttp::on_btnDown_clicked()
{
QString urlSpec = ui->lineEditUrl->text().trimmed(); //去掉字符串的首尾的空格
if (urlSpec.isEmpty()) {
QMessageBox::information(this, "提示", "下载地址URL为NULL");
return;
}
QUrl url = QUrl::fromUserInput(urlSpec);
if (!url.isValid()) {
QMessageBox::information(this, "提示", QString("无效URL: %1 \n 错误信息: %2").arg(urlSpec, url.errorString()));
return;
}
QString dir = ui->lineEditFile->text().trimmed();
if (dir.isEmpty()) {
QMessageBox::information(this, "提示", "保存地址为空");
return;
}
QString fileFileName = dir + url.fileName(); //文件保存地址 + 文件名
if (QFile::exists(fileFileName))
QFile::remove(fileFileName);
m_file = new QFile(fileFileName); //创建临时文件
if (!m_file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, "提示", "打开临时文件错误");
return;
}
ui->btnDown->setEnabled(false);
m_reply = m_networkManager->get(QNetworkRequest(url)); //发送get网络请求创建网络响应
connect(m_reply, SIGNAL(finished()), this, SLOT(onFinished()));
connect(m_reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(m_reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(onDownloadProgress(qint64,qint64)));
}
//默认的保存路径
void ExHttp::on_btnFile_clicked()
{
QString currPath = QDir::currentPath();
QDir dir(currPath);
dir.mkdir("temp");
ui->lineEditFile->setText(currPath + "/temp/");
}
//网络响应结束
void ExHttp::onFinished()
{
QFileInfo fileInfo;
fileInfo.setFile(m_file->fileName());
m_file->close();
delete m_file;
m_file = nullptr;
m_reply->deleteLater();
m_reply = nullptr;
if (ui->checkBox->isChecked()) //勾选了,下载完成之后,打开下载的文件 //absoluteFilePath() 返回包含文件名的绝对路径。
QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absoluteFilePath())); //使用默认软件的打开下载的文件
ui->btnDown->setEnabled(true);
}
//读取下载的数据
void ExHttp::onReadyRead()
{
m_file->write(m_reply->readAll()); //将返回的数据进行读取,写入到临时文件中
}
//下载进程
void ExHttp::onDownloadProgress(qint64 bytesRea, qint64 totalBytes)
{
ui->progressBar->setMaximum(totalBytes);
ui->progressBar->setValue(bytesRea);
}
void ExHttp::on_lineEditUrl_textChanged(const QString &arg1)
{
ui->progressBar->setMaximum(100);
ui->progressBar->setValue(0);
}

40
QtHttpEx/ExHttp.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef EXHTTP_H
#define EXHTTP_H
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QFile>
#include <QUrl>
#include <QDir>
namespace Ui {
class ExHttp;
}
class ExHttp : public QMainWindow
{
Q_OBJECT
public:
explicit ExHttp(QWidget *parent = nullptr);
~ExHttp();
private slots:
void on_btnDown_clicked(); //下载文件
void on_btnFile_clicked(); //默认的保存路径
void on_lineEditUrl_textChanged(const QString &arg1);
void onFinished(); //网络响应结束
void onReadyRead(); //读取下载的数据
void onDownloadProgress(qint64 bytesRea, qint64 totalBytes); //下载进程
private:
Ui::ExHttp *ui;
QNetworkAccessManager* m_networkManager; //网络管理
QNetworkReply* m_reply; //网络响应
QFile* m_file; //下载保存的临时文件
};
#endif // EXHTTP_H

89
QtHttpEx/ExHttp.ui Normal file
View File

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ExHttp</class>
<widget class="QMainWindow" name="ExHttp">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>555</width>
<height>111</height>
</rect>
</property>
<property name="windowTitle">
<string>ExHttp</string>
</property>
<widget class="QWidget" name="centralWidget">
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout" rowstretch="1,8,1">
<item row="1" column="1">
<widget class="QLineEdit" name="lineEditFile"/>
</item>
<item row="1" column="2">
<widget class="QPushButton" name="btnFile">
<property name="text">
<string>默认路径</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="lineEditUrl">
<property name="text">
<string>http://download.qt.io/archive/vsaddin/2.4.2/md5sums.txt</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>URL</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QPushButton" name="btnDown">
<property name="text">
<string>下载</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>保存路径:</string>
</property>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QProgressBar" name="progressBar">
<property name="value">
<number>0</number>
</property>
<property name="textVisible">
<bool>true</bool>
</property>
<property name="textDirection">
<enum>QProgressBar::TopToBottom</enum>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QCheckBox" name="checkBox">
<property name="text">
<string>结束之后打开</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>

56
QtHttpEx/QtHttpEx.pro Normal file
View File

@ -0,0 +1,56 @@
#-------------------------------------------------
#
# Project created by QtCreator 2019-12-05T21:58:28
#
#-------------------------------------------------
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = QtHttpEx
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
CONFIG += c++11
SOURCES += \
main.cpp \
ExHttp.cpp
HEADERS += \
ExHttp.h
FORMS += \
ExHttp.ui
macx {
ICON = images/icon.icns
}
unix:!macx{
# linux only
}
win32 {
RC_ICONS = images/icon.ico
}
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
RESOURCES += \
resources.qrc

BIN
QtHttpEx/images/Image1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 603 B

BIN
QtHttpEx/images/Image2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

BIN
QtHttpEx/images/Image3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 352 B

BIN
QtHttpEx/images/Image4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 803 B

BIN
QtHttpEx/images/Image5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

BIN
QtHttpEx/images/Image6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 B

BIN
QtHttpEx/images/icon.icns Executable file

Binary file not shown.

BIN
QtHttpEx/images/icon.ico Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

11
QtHttpEx/main.cpp Normal file
View File

@ -0,0 +1,11 @@
#include "ExHttp.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ExHttp w;
w.show();
return a.exec();
}

6
QtHttpEx/resources.qrc Normal file
View File

@ -0,0 +1,6 @@
<RCC>
<qresource prefix="/">
<file>images/Image6.png</file>
<file>images/Image3.png</file>
</qresource>
</RCC>

View File

@ -75,8 +75,9 @@
## 第四部分:网络编程
- 主机信息查询QHostInfo和QNetworkInterface查询IP等【QtQHostInfoEx】
- TCP通信之QTcpServer和QTcpSocket服务器和客户端通讯【QtTcpEx】
- 主机信息查询`QHostInfo`和`QNetworkInterface`查询IP等【QtQHostInfoEx】
- `TCP`通信之`QTcpServer`和`QTcpSocket`服务器和客户端通讯【QtTcpEx】
- `QNetworkAccessManager`/`QNetworkReply`/`QNetworkRequest`实现高层网络的操作
<br>