这个例子演示了一个简单的HTTP客户端如何从远程主机获取文件。
main.cpp
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include <QApplication>
#include <QDir>
#include <QScreen>
#include "httpwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
HttpWindow httpWin;//HttpWindow 是一个自定义的窗口类型,可能是用于显示网页内容的窗口
const QRect availableSize = httpWin.screen()->availableGeometry();
httpWin.resize(availableSize.width() / 5, availableSize.height() / 5);//将 httpWin 窗口的大小调整为屏幕可用尺寸的1/5
httpWin.move((availableSize.width() - httpWin.width()) / 2, (availableSize.height() - httpWin.height()) / 2);//将 httpWin 窗口移动到屏幕的中心位置
httpWin.show();
return app.exec();
}
httpwindow.h
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifndef HTTPWINDOW_H
#define HTTPWINDOW_H
#include <QProgressDialog>
#include <QNetworkAccessManager>
#include <QUrl>
#include <memory>
//这些类都位于QT_BEGIN_NAMESPACE 和 QT_END_NAMESPACE 之间,表示它们属于 Qt 框架的命名空间
QT_BEGIN_NAMESPACE
class QFile;
class QLabel;
class QLineEdit;
class QPushButton;
class QSslError;
class QAuthenticator;
class QNetworkReply;
class QCheckBox;
//条件编译指令,检查在编译 Qt 框架时是否启用了网络代理的支持。
//在编译 Qt 的时候,如果定义了 QT_CONFIG(networkproxy) 宏为真,那么就会执行这个条件块中的代码。
#if QT_CONFIG(networkproxy)
class QNetworkProxy;//QNetworkProxy 类是 Qt 框架中用于管理网络代理设置的类,比如 HTTP 代理、SOCKS 代理
#endif
QT_END_NAMESPACE
class ProgressDialog : public QProgressDialog {
Q_OBJECT
public:
//explicit: 表示这个构造函数是显式构造函数,意味着它不会隐式地执行类型转换。调用这个构造函数时必须显式地使用构造函数的参数。
explicit ProgressDialog(const QUrl &url, QWidget *parent = nullptr);
public slots:
//networkReplyProgress函数是Qt框架中QNetworkReply对象发出的一个信号,用于提供网络请求的进度信息。
//bytesRead: 已经读取的字节数 totalBytes: 预期要读取的总字节数。
void networkReplyProgress(qint64 bytesRead, qint64 totalBytes);
};
class HttpWindow : public QDialog
{
Q_OBJECT
public:
explicit HttpWindow(QWidget *parent = nullptr);
~HttpWindow();
void startRequest(const QUrl &requestedUrl);
private slots:
void downloadFile();
void cancelDownload();
void httpFinished();
void httpReadyRead();
void enableDownloadButton();
void slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator);
//QT_CONFIG(ssl)是一个Qt框架提供的宏
/*#if 指令用于检查某个宏是否已定义,或者其值是否满足某个条件。
* 如果条件为真,则包含#if和#endif之间的代码块。如果条件为假,则排除该代码块。*/
#if QT_CONFIG(ssl)
void sslErrors(const QList<QSslError> &errors);
#endif
#if QT_CONFIG(networkproxy)
void slotProxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator);
#endif
private:
std::unique_ptr<QFile> openFileForWrite(const QString &fileName);
QLabel *statusLabel;
QLineEdit *urlLineEdit;
QPushButton *downloadButton;
QCheckBox *launchCheckBox;
QLineEdit *defaultFileLineEdit;
QLineEdit *downloadDirectoryLineEdit;
/*QUrl 是 Qt 框架中用于表示和操作 URL 的类。它提供了以下主要功能:
1、解析和构建完整的 URL 字符串。
2、访问和修改 URL 的各个组成部分,如协议、主机、端口、路径、查询参数等。
3、对 URL 进行编码和解码操作。
4、比较和测试 URL 的有效性。*/
QUrl url;
/*QNetworkAccessManager 是 Qt 框架中用于处理网络请求的核心类。它提供了以下功能:
1、发送 HTTP、HTTPS、FTP 等各种协议的网络请求