Overview
Qt Network
The module provides classes for writingTCP/IP
clients and servers. It provides lower-level classes, such as QTcpSocket
, QTcpServer
, and QUdpSocket
, to represent low-level network concepts, as well as high-level Classes, such as QNetworkRequest
, QNetworkReply
, and QNetworkAccessManager
, perform network operations using common protocols. It also provides classes such as QNetworkConfiguration
, QNetworkConfigurationManager
, and QNetworkSession
that implement bearer management.
HTTP
Advanced network operations for and FTP
网络访问API
is a collection of classes used to perform common network operations. API
Provides an abstraction layer for the specific operations and protocols used (for example, getting and publishing data through HTTP
), developers only need to use the classes it provides , functions or signals can complete the operation without knowing how the underlying implementation is implemented.
Network requests are represented by the QNetworkRequest
class, which also acts as a general container for information related to the request, such as any header information and encryption used. The URL
specified when constructing the request object determines the protocol used by the request. Currently HTTP
, FTP
and 本地文件url
are supported for uploading and downloading.
Coordination of network operations is performed by QNetworkAccessManager
classes. Once a request is created, use this class to dispatch the request and emit signals to report its progress. The manager also coordinates the use ofcookie
storing data on clients, authentication requests, and the use of proxies.
Replies to network requests are represented by QNetworkReply
classes; these are created by QNetworkAccessManager
when the request is dispatched. QNetworkReply
The provided signals can be used to monitor each reply individually, or the developer can choose to use the manager's signals instead for this purpose and drop references to the replies. Since QNetworkReply
is a subclass of QIODevice
, responses can be processed synchronously or asynchronously; that is, as blocking or non-blocking operations.
Each application or library can create one or more QNetworkAccessManager
instances to handle network communications.
HTTP
HTTP (Hypertext Transfer Protocol) is a protocol used to transmit hypermedia documents (such as HTML). It is a client-server protocol that communicates between web browsers and web servers.
The basic working principle of HTTP is that the client sends a request to the server, the server processes the request and sends a response to the client. The contents of requests and responses are composed of a series of messages, including request lines, request headers, and request bodies (in requests), as well as status lines, response headers, and response bodies (in responses).
HTTP communication is stateless, which means that each request is independent and the server does not retain any state information between different requests. To solve this problem, HTTP introduced some mechanisms, such as Cookie
and Session
, to share state information between different requests.
HTTP has multiple versions, the most commonly used isHTTP/1.1
. It supports functions such as persistent connections, transmission compression, and chunked transmission encoding, which can improve transmission efficiency. The latest version is HTTP/2
, which introduces new features such as binary protocol and multiplexing.
In addition to transmitting hypermedia documents, HTTP can also be used for other purposes, such as API calls, file uploads and downloads, etc.
The following is an example of HTTP communication through the network access interface:
In .pro
add:
QT += network
In the header file, createQNetworkAccessManager
and declarereplyFinished(QNetworkReply* reply)
the slot.
#include <QMainWindow>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkAccessManager>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void replyFinished(QNetworkReply* reply);
private:
Ui::MainWindow *ui;
QNetworkAccessManager* m_pAceessManager;
};
Initialize and implement slots in the source file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_pAceessManager = new QNetworkAccessManager(this);
// 当get完成时,进入replyFinished函数
connect(m_pAceessManager, &QNetworkAccessManager::finished, this, &MainWindow::replyFinished);
m_pAceessManager->get(QNetworkRequest(QUrl("http://httpbin.org/")));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::replyFinished(QNetworkReply *reply)
{
ui->textBrowser->setText(QString(reply->readAll()));
reply->deleteLater();
}
After is executed, the display is as follows:
In addition to the get()
function, the manager also provides http post
request. /span>Function. requestedfunction, requestedpost()
function, http put
put()
http delete
deleteResource()
Example of implementing file download and displaying progress
- First is the UI
- Add the following slot function in the header file
// 连接QNetworkReply的finished信号
void slot_httpFinished();
// 连接QNetworkReply的readyRead信号
void slot_httpReadyRead();
// 连接QNetworkReply的updateDataReadProgress信号
void slot_updataProgress(qint64, qint64);
// 下载按钮槽函数
void on_btn_download_clicked();
- Add the following private functions and member variables to the header file
private:
// 开始请求
void startRequest(const QUrl& url);
QNetworkAccessManager* m_pAceessManager; // 网络访问管理
QNetworkReply* m_pReply; // 回复
QFile* m_pFile; // 文件指针
QUrl m_url; // url
- Initialized in the constructor
m_pAceessManager = new QNetworkAccessManager(this);
ui->progressBar->setValue(0);
- Implement the above slot functions and private member functions
void MainWindow::startRequest(const QUrl &url)
{
m_pReply = m_pAceessManager->get(QNetworkRequest(url));
connect(m_pReply, &QNetworkReply::readyRead, this, &MainWindow::slot_httpReadyRead);
connect(m_pReply, &QNetworkReply::downloadProgress, this, &MainWindow::slot_updataProgress);
connect(m_pReply, &QNetworkReply::finished, this, &MainWindow::slot_httpFinished);
}
void MainWindow::on_btn_download_clicked()
{
m_url = ui->lineEdit->text();
QFileInfo fileInfo(m_url.path());
QString fileName(fileInfo.fileName());
if(fileName.isEmpty())
{
fileName = "helloworld.html";
}
m_pFile = new QFile(fileName);
if(m_pFile->open(QIODevice::WriteOnly))
{
startRequest(m_url);
}
}
void MainWindow::slot_httpFinished()
{
if(m_pFile)
{
m_pFile->close();
m_pFile->deleteLater();
m_pFile = nullptr;
}
m_pReply->deleteLater();
m_pReply = nullptr;
}
void MainWindow::slot_httpReadyRead()
{
if(m_pFile)
{
m_pFile->write(m_pReply->readAll());
}
}
void MainWindow::slot_updataProgress(qint64 readSize, qint64 totalBytes)
{
ui->progressBar->setMaximum(totalBytes);
ui->progressBar->setValue(readSize);
}
Run the program and click to download
The display is as follows:
FTP
FTP protocol (File Transfer Protocol) is one of the standard protocols used for file transfer in computer networks. It allows users to transfer files from one computer to another over a TCP/IP network. The FTP protocol consists of two parts: control connection and data transmission connection.
Control connections are used for communication between commands and responses, including user authentication, file directory browsing, and file operations. Control connections use the default port number 21.
The data transfer connection is used for the actual file transfer. In the FTP protocol, there are two different data transmission modes: active mode and passive mode. In active mode, the server initiates a data connection on port 20, while the client waits for a connection on the high port. In passive mode, the server waits for connections on the high port, while the client initiates a data connection on port 20.
The FTP protocol supports most operating systems, including Windows, Linux, and macOS. It provides many features such as file upload and download, file renaming, file deletion, etc. In addition, the FTP protocol also supports anonymous login, allowing users to use anonymous identities to access files on public FTP servers.
However, since the FTP protocol has poor security and is vulnerable to data leaks and malicious attacks, it is usually recommended to use more secure protocols, such as SFTP (SSH File Transfer Protocol) or FTPS (FTP over SSL/TLS). These protocols add security features such as encryption and authentication to the FTP protocol to provide more reliable file transfer.