2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
1. Http is the abbreviation of Hypertext Transfer Protocol, which defines the communication specifications between browsers and web servers. It is a simple request-response protocol that usually runs on TCP.
Function: It specifies the information transmission standards between WWW servers and browsers, and is a protocol that both parties abide by.
2.How does http work?HTTP is based on the client/server model and is connection-oriented. HTTP transaction processing flow
1. Using QNetworkAccessManager and QNetworkReply classes:
2. Using QHttpEngine and QHttpNetworkRequest/Reply classes (lower level):
Generally speaking, for simple HTTP operations, it is sufficient to use the high-level QNetworkAccessManager interface. It can conveniently handle common needs.
If you need lower-level control, such as customizing the HTTP engine or request/response details, you can use lower-level classes such as QHttpEngine.
In short, Qt provides a complete HTTP client implementation, and developers can choose a more appropriate interface for network communication operations according to actual needs. This provides good support for developing Qt applications.
The first type: QNetworkAccessManager network connection manager, 2 behaviors: get/post to obtain or submit a request, and the returned object QNetworkReply contains various connection information.
The second type: QHttpEngine only manages connection requests and is not responsible for sending them.
Use QHttpNetworkRequest to build a request and send it through QHttpEngine.
Parse the returned QHttpNetworkReply to get the response.
- #ifndef MAINWINDOW_H
- #define MAINWINDOW_H
-
- #include <QMainWindow>
-
-
- #include <QtNetwork> // 提供编程TCP/IP客户端和服务器的类
- #include <QUrl> // 提供接口使用URLs
-
-
- QT_BEGIN_NAMESPACE
- namespace Ui { class MainWindow; }
- QT_END_NAMESPACE
-
- class MainWindow : public QMainWindow
- {
- Q_OBJECT
-
- public:
- MainWindow(QWidget *parent = nullptr);
- ~MainWindow();
-
-
- private slots:
- void on_pushButton_clicked();
-
- private:
- Ui::MainWindow *ui;
- QNetworkAccessManager* accesssMgr;
- };
- #endif // MAINWINDOW_H
-
-
- #include "mainwindow.h"
- #include "ui_mainwindow.h"
-
- MainWindow::MainWindow(QWidget *parent)
- : QMainWindow(parent)
- , ui(new Ui::MainWindow)
- {
- ui->setupUi(this);
- accesssMgr =new QNetworkAccessManager(this);
-
- QObject::connect(accesssMgr,QOverload<QNetworkReply*>::of(&QNetworkAccessManager::finished),this,
- [this](QNetworkReply* reply){
- QString read=reply->readAll();
- ui->textBrowser->setText(read);
- reply->deleteLater(); //释放
- });
-
- }
-
- MainWindow::~MainWindow()
- {
- delete ui;
- }
-
-
- void MainWindow::on_pushButton_clicked()
- {
- ui->label->setText("数据正在下载中,请耐心等待......");
- QString url=ui->textEdit->toPlainText();
- qDebug()<<url;
- accesssMgr->get(QNetworkRequest(QUrl(url)));
- }
- #include "httpserver.h"
-
- HttpServer::HttpServer(QObject *parent) : QObject(parent)
- {
- server =new QTcpServer(this);
- //连接回调
- connect(server,&QTcpServer::newConnection,this,&HttpServer::MyselfNewConnectCalllSlot);
- //开始监听
- if(!server->listen(QHostAddress::Any,8088))
- {
- qDebug()<<"n致命错误:Web服务器没有启动,请重新检查!"<<endl;
- }
- else
- {
- qDebug()<<"n正常启动:Web服务器端口:8088,等待客户端连接......"<<endl;;
- }
- }
- void HttpServer::MyselfNewConnectCalllSlot(){
- socket = server->nextPendingConnection(); //获取连接
- while(!(socket->waitForReadyRead(100))); //等待套接字是否有可读数据。 一直阻塞线程等待,直到有可读数据到达套接字,或者超时返回。
-
- QString webdata;
- webdata.resize(1000);
- webdata=socket->read(1000);
-
- qDebug()<<"正常运行:从浏览器读取数据信息......"<<webdata;
-
- //封装http协议
- socket->write("HTTP/1.1 200 OKrn");
- socket->write("Content-Type: text/htmlrn");
- socket->write("Connection: closern");
- socket->write("Refresh: 3rnrn"); // 每秒刷新Web浏览器
- socket->write("<!DOCTYPE>"
- "<html>"
- "<header>"
- "<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>"
- "<title>HttpServer</title>"
- "</header>"
- "<body>客户端已经连接HttpSever服务器秒数为:");
-
- QByteArray byte;
- static qint16 icount=0;
- byte.setNum(icount++);
- socket->write(byte);
- socket->write("</html>");
- /*
- flush() 不会等待数据真正发送出去,只是把数据从本地缓冲区 flush 到内核缓冲区。
- 如果输出缓冲区没有数据,flush() 有可能不做任何操作。
- 调用 flush() 可以确保目前为止写到 socket 的所有数据都发送给对端,而不是 buffered 在本地。
- 一般在发送完请求或应答后调用,保证数据及时发送出去。
- */
- socket->flush(); //刷新 socket 对象的输出缓冲区。 并发送
-
-
- connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
- socket->disconnectFromHost();
- }
HTTP is an application layer protocol based on TCP, so TCP classes are used and the protocol encapsulation is fixed.
- 请求:
- GET /index.html HTTP/1.1
- Host: www.example.com
- User-Agent: Mozilla/5.0...
- Accept: text/html
-
- 响应:
- HTTP/1.1 200 OK
- Date: Mon, 27 Jan 2020 08:12:31 GMT
- Server: Apache/2.4.1 (Unix)
- Last-Modified: Wed, 22 Jul 2020 19:15:56 GMT
- ETag: "49092-5b6-52c65aa32f280"
- Accept-Ranges: bytes
- Content-Length: 438
- Connection: close
- Content-Type: text/html; charset=UTF-8
-
- <html>
- <head>
- <title>Welcome to example.com!</title>
- </head>
- <body>
- <h1>Hello World!</h1>
- <p>This is the hello world page for an example website.</p>
- </body>
- </html>
-
-
- 这个示例演示了一个简单的HTTP请求和响应过程:
- 客户端发送GET请求获取index.html页面
- 服务器返回200状态码,表示请求成功
- 返回各种报头如日期、服务器信息等
- 返回HTML页面内容作为响应体
The main classes for Qt HTTP programming are QNetworkAccessManager, QNetworkRequest, and QNetworkReply.
QNetworkAccessManager:
Manages connections and requests to the network. Sends and receives data.
Provides high-level functions such as get(), post(), put() to initiate HTTP requests.
Signals: finished(), authenticationRequired()等。
QNetworkRequest:
Represents an HTTP request, including URL, headers and other properties.
Set the request method, content type, header information, etc.
QNetworkReply:
Represents an HTTP response. Returns status code and content.
Signals: downloadProgress(), error() and other notifications of processing results.
Functions such as readAll() read the response content.
Main steps of use:
Create an instance of the QNetworkAccessManager object.
Create a QNetworkRequest object and set the URL and properties.
Call QNetworkAccessManager::get() or post() to make a request.
Listen to QNetworkReply signals to get the results.
Read the content through QNetworkReply, or handle the error.
Delete QNetworkReply and Request objects to prevent memory leaks.