How to use Qt for HTTP communication

1 Introduction to HTTP protocol

1.1 History and development of HTTP protocol

HTTP was born in 1991, and the initial version number was 0.9. In 1996, HTTP/1.0 was born, adding HEAD, POST and other methods, adding response status codes and introducing HTTP Header (HTTP header). HTTP/1.1, launched in 1999, introduced long connections, concurrent connections, pipeline mechanisms, etc. In 2015, HTTP/2 was released, which no longer uses ASCII encoding to transmit data by default, but instead transmits binary data. When HTTP/2 sends a request, it will encapsulate the content of each request into numbered frames and then send them simultaneously. This method of using one connection to send multiple requests is called "multiplexing". HTTP/3 was released in 2018. HTTP/3 changes the underlying TCP protocol to UDP protocol.

1.2 Characteristics of HTTP protocol

The HTTP protocol is a stateless protocol based on the request and response model. The request is initiated by the client and the server responds to the request. Stateless means that after the interaction between the client and the server is completed, no state information will be retained between the two. The communication method of HTTP protocol is simple, flexible and has good scalability.

1.3 Working process of HTTP

(1) Establish a TCP connection.
Analyze the domain name of the server and obtain the server IP address. Then establish a TCP connection with the server.
(2) The browser sends an HTTP request to the server. Includes document information required by the client and additional information such as Accept and User-Agent.
(3) Server response. The response content includes the version number of the HTTP protocol, response status code, requested document content, etc.
(4) The server closes the HTTP connection.
(5) Repeat steps 2 to 4. The browser requests and receives the HTML, CSS, JS, images and other documents responded by the server, renders the page, or saves the received response file.
(6) The server closes the TCP connection. The TCP connection is closed when the server decides it no longer wants to communicate with the browser.

1.4 Request message

The HTTP/1.1 request message consists of four parts. The request line includes the request method, URL, and protocol version. The header is located after the request line, and each line contains a header field name and corresponding value. The entity is the data of the request message and is used in the POST method. If the request method is GET, the request data is empty. Separate the entity from the header with a blank line. Spaces, carriage returns and line feeds in the message cannot be omitted.
The request method is the way for the client to explain its intention to the server through the request method. Commonly used methods include GET, POST, PUT, DELETE and other methods.
The header consists of a series of "field:value", which plays the role of transmitting additional information.

1.5 Response message

After the server receives the request message, it will respond and send a response message. The response message is almost identical in structure to the request message, except that the functions of individual fields are different.
The response message consists of three parts. The status line includes protocol version, status code, and status phrase. The header is similar to the header in the request message. It consists of a series of "field:value" and plays the role of transmitting additional information. The entity is the data of the response message and is used in the GET method. Separate the entity from the header with a blank line. Spaces, carriage returns and line feeds in the message cannot be omitted.

2 Using Qt for HTTP communication

2.1 Qt’s HTTP communication class

Qt's network module provides HTTP communication classes QNetworkRequest, QnetworkAccessManagerand QNetworkReply. To use these classes, you need to reference the network module in the project's pro file:
QT += network
and reference the header file in the source file:

#include <QNetworkRequest>
#include <QNetworkAccessManager> 
#include <QNetworkReply>

2.2 HTTP communication process

The process of using these classes for HTTP communication can be divided into three steps:
(1) Use QNetworkRequestclass objects to create network requests.
(2) Use QNetworkAccessManagerclass objects to perform network communication. QNetworkAccessManagerThe class object is used to manage the HTTP communication of the program, and provides get()、post()、put()multiple functions, corresponding to GET、POST、PUTthe methods of the HTTP protocol. Calling these functions will return an QNetworkReplyobject that holds the server's response data. A program only needs one QnetworkAccessManagerclass object. QNetworkAccessManagerThe class also provides some signals, such as finished()signals for receiving server responses, signals for changes in network status networkAccessibleChanged(), etc.
(3) Receive server response through QNetworkReply.
QNetworkAccessManagerThe class object will save the server's response message in a QNetworkReplyclass object and emit the pointer of finished(QNetworkReply*)this class object through a signal. The class is also a subclass, and you can call the read() function to read the information returned by the server just like operating the serial port. The class also provides signals such as finished() and readyRead(), which can perform corresponding operations based on the signals.QNetworkReplyQNetworkReplyQIODeviceQNetworkReply

3 JSON

JSON is a lightweight data exchange format that uses a text format that is completely independent of programming languages ​​to store and represent data, and can efficiently transfer large amounts of data.
JSON data type

(1) Numeric value: that is, decimal number, such as 12, 3.14, 5.2e4, etc. In JSON, the value can be negative, it can have a decimal part, and e or E can be used to represent the exponent part, but it cannot have leading 0s. JSON does not distinguish between integers and floating point numbers.

(2) String: zero or more Unicode characters surrounded by English double quotes, such as "Hello" or "".

(3) Boolean value: true or false. JSON boolean values ​​must be lowercase letters.

(4) Array: Zero or more ordered values, each value can be of any type. The array is surrounded by English square brackets, and the elements are separated by English commas, such as: ["aa", "bb", "cc"], [[3, 1], [4, 1], [5, 9] ]wait.

(5) Object: The object is surrounded by English curly braces and contains several unordered key-value pairs. Use commas to separate different key-value pairs. The key can only be a string, and the value can be the various types of data mentioned above, or it can be another object (that is, a nested object).

3.1 Introduction to cJSON library

cJSON is a JSON operation library written in C language. It is lightweight, portable, and single-file, and can easily generate and parse JSON data. There are only two source code files of the cJSON library, namely cJSON.h and cJSON.c. When using, just add these two files to the project.

3.2 Design ideas and data structure of cJSON library

When cJSON generates and parses JSON data, it does not process the entire JSON data as a whole, but splits the entire JSON data into key-value pairs one by one. Each key-value pair is stored in a cJSON structure. According to the hierarchical relationship of JSON data, cJSON structures at the same level form a doubly linked list, and linked lists at different levels are connected through pointers.

3.3 How to use the cJSON library

The cJSON library provides a series of APIs to generate and parse JSON data. Among them, the APIs for generating JSON data include cJSON_CreateObject(), cJSON_CreateArray(), cJSON_CreateString(), cJSON_CreateNumber()etc.; JSONthe APIs for parsing data include cJSON_Parse(), , cJSON_GetObjectItem(), cJSON_GetArraySize()etc. Using the cJSON library, you can easily process JSON data in C language.

Guess you like

Origin blog.csdn.net/weixin_40933653/article/details/133469151