Technology Sharing

Qt http network programming

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Learning objectives: Qt HTTP network programming

Learning Content

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. The client establishes a connection with the server;
  2. The client makes a request to the server;
  3. The server accepts the request and returns the corresponding file as a response:
  4. The client and server close the connection.

Qt implements HTTP operations in two ways

1. Using QNetworkAccessManager and QNetworkReply classes:

  1. - QNetworkAccessManager is Qt's network access manager, responsible for sending and receiving HTTP/HTTPS requests.
  2. - Initiate GET/POST requests through QNetworkAccessManager::get/post, etc., and return a QNetworkReply object.
  3. - Get the response code, header information, content, etc. from QNetworkReply. Implement synchronous and asynchronous requests.

2. Using QHttpEngine and QHttpNetworkRequest/Reply classes (lower level):

  1. - QHttpEngine is responsible for managing HTTP connections and processing requests.
  2. - Use QHttpNetworkRequest to build a request and send it through QHttpEngine.
  3. - Parse the returned QHttpNetworkReply to get the response.

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.

Summarize:

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.

Project effects and core code

http reader

http server

Core code

http reader

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3. #include <QMainWindow>
  4. #include <QtNetwork> // 提供编程TCP/IP客户端和服务器的类
  5. #include <QUrl> // 提供接口使用URLs
  6. QT_BEGIN_NAMESPACE
  7. namespace Ui { class MainWindow; }
  8. QT_END_NAMESPACE
  9. class MainWindow : public QMainWindow
  10. {
  11. Q_OBJECT
  12. public:
  13. MainWindow(QWidget *parent = nullptr);
  14. ~MainWindow();
  15. private slots:
  16. void on_pushButton_clicked();
  17. private:
  18. Ui::MainWindow *ui;
  19. QNetworkAccessManager* accesssMgr;
  20. };
  21. #endif // MAINWINDOW_H
  22. #include "mainwindow.h"
  23. #include "ui_mainwindow.h"
  24. MainWindow::MainWindow(QWidget *parent)
  25. : QMainWindow(parent)
  26. , ui(new Ui::MainWindow)
  27. {
  28. ui->setupUi(this);
  29. accesssMgr =new QNetworkAccessManager(this);
  30. QObject::connect(accesssMgr,QOverload<QNetworkReply*>::of(&QNetworkAccessManager::finished),this,
  31. [this](QNetworkReply* reply){
  32. QString read=reply->readAll();
  33. ui->textBrowser->setText(read);
  34. reply->deleteLater(); //释放
  35. });
  36. }
  37. MainWindow::~MainWindow()
  38. {
  39. delete ui;
  40. }
  41. void MainWindow::on_pushButton_clicked()
  42. {
  43. ui->label->setText("数据正在下载中,请耐心等待......");
  44. QString url=ui->textEdit->toPlainText();
  45. qDebug()<<url;
  46. accesssMgr->get(QNetworkRequest(QUrl(url)));
  47. }

http server

  1. #include "httpserver.h"
  2. HttpServer::HttpServer(QObject *parent) : QObject(parent)
  3. {
  4. server =new QTcpServer(this);
  5. //连接回调
  6. connect(server,&QTcpServer::newConnection,this,&HttpServer::MyselfNewConnectCalllSlot);
  7. //开始监听
  8. if(!server->listen(QHostAddress::Any,8088))
  9. {
  10. qDebug()<<"n致命错误:Web服务器没有启动,请重新检查!"<<endl;
  11. }
  12. else
  13. {
  14. qDebug()<<"n正常启动:Web服务器端口:8088,等待客户端连接......"<<endl;;
  15. }
  16. }
  17. void HttpServer::MyselfNewConnectCalllSlot(){
  18. socket = server->nextPendingConnection(); //获取连接
  19. while(!(socket->waitForReadyRead(100))); //等待套接字是否有可读数据。 一直阻塞线程等待,直到有可读数据到达套接字,或者超时返回。
  20. QString webdata;
  21. webdata.resize(1000);
  22. webdata=socket->read(1000);
  23. qDebug()<<"正常运行:从浏览器读取数据信息......"<<webdata;
  24. //封装http协议
  25. socket->write("HTTP/1.1 200 OKrn");
  26. socket->write("Content-Type: text/htmlrn");
  27. socket->write("Connection: closern");
  28. socket->write("Refresh: 3rnrn"); // 每秒刷新Web浏览器
  29. socket->write("<!DOCTYPE>"
  30. "<html>"
  31. "<header>"
  32. "<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>"
  33. "<title>HttpServer</title>"
  34. "</header>"
  35. "<body>客户端已经连接HttpSever服务器秒数为:");
  36. QByteArray byte;
  37. static qint16 icount=0;
  38. byte.setNum(icount++);
  39. socket->write(byte);
  40. socket->write("</html>");
  41. /*
  42. flush() 不会等待数据真正发送出去,只是把数据从本地缓冲区 flush 到内核缓冲区。
  43. 如果输出缓冲区没有数据,flush() 有可能不做任何操作。
  44. 调用 flush() 可以确保目前为止写到 socket 的所有数据都发送给对端,而不是 buffered 在本地。
  45. 一般在发送完请求或应答后调用,保证数据及时发送出去。
  46. */
  47. socket->flush(); //刷新 socket 对象的输出缓冲区。 并发送
  48. connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
  49. socket->disconnectFromHost();
  50. }

 

Summarize

HTTP is an application layer protocol based on TCP, so TCP classes are used and the protocol encapsulation is fixed.

  1. 请求:
  2. GET /index.html HTTP/1.1
  3. Host: www.example.com
  4. User-Agent: Mozilla/5.0...
  5. Accept: text/html
  6. 响应:
  7. HTTP/1.1 200 OK
  8. Date: Mon, 27 Jan 2020 08:12:31 GMT
  9. Server: Apache/2.4.1 (Unix)
  10. Last-Modified: Wed, 22 Jul 2020 19:15:56 GMT
  11. ETag: "49092-5b6-52c65aa32f280"
  12. Accept-Ranges: bytes
  13. Content-Length: 438
  14. Connection: close
  15. Content-Type: text/html; charset=UTF-8
  16. <html>
  17. <head>
  18. <title>Welcome to example.com!</title>
  19. </head>
  20. <body>
  21. <h1>Hello World!</h1>
  22. <p>This is the hello world page for an example website.</p>
  23. </body>
  24. </html>
  25. 这个示例演示了一个简单的HTTP请求和响应过程:
  26. 客户端发送GET请求获取index.html页面
  27. 服务器返回200状态码,表示请求成功
  28. 返回各种报头如日期、服务器信息等
  29. 返回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:

  1. Create an instance of the QNetworkAccessManager object.

  2. Create a QNetworkRequest object and set the URL and properties.

  3. Call QNetworkAccessManager::get() or post() to make a request.

  4. Listen to QNetworkReply signals to get the results.

  5. Read the content through QNetworkReply, or handle the error.

  6. Delete QNetworkReply and Request objects to prevent memory leaks.

Finally, attach the source code link
If it helps you, please give me a star

Qt demo: learning qt process (gitee.com)