Network programming in QT sends Get and Post requests of Http protocol


The product developed using QT is ultimately used as a client, and a big function is to interact with the back-end server.
The currently used QT versions are as follows:
Insert image description here

HTTP protocol

Hyper Text Transfer Protocol (HTTP) is a simple request-response protocol that usually runs on top of TCP. It specifies what kind of messages the client may send to the server and what kind of response it gets. The headers of request and response messages are given in ASCII form; the message contents have a MIME-like format.
Insert image description here

GET request

GET requests data from the specified resource. If necessary, query string parameters can be appended to the end of the URL to send information to the server. Because the parameters of GET are placed in the URL, the privacy and security are poor. The length of the requested data is limited. Different browsers and servers are different. It is generally limited to 2~8K, and the more common limit is within 1K. .

POST request

POST submits data to be processed to the specified resource. POST requests should submit data as the body of the request. The request body can include a lot of data, and the data format is not limited. There is no length limit for POST requests, and the request data is placed in the body.

Processing of HTTP protocol in QT

Qt provides QNetworkAccessManager, QNetworkRequest and QNetworkReply for applications to handle network access.

1.QNetworkAccessManager

QNetworkAccessManager provides the ability for applications to send requests over the network.

2.QNetworkRequest

QNetworkRequest holds the information needed to send a request over the network. It contains a URL and some auxiliary information that can be used to modify the request.

3.QNetworkReply

The QNetworkReply class encapsulates reply information related to requests issued using QNetworkAccessManager. QNetworkReply is a subclass of QIODevice, which means that once the data is read from the object, it is no longer retained by the device. Therefore, it is the application's responsibility to retain this data if required.

QT implements GET request and POST request

Project structure preview:
Insert image description here
Insert image description here
头文件httpoperate.h内容:

#ifndef HTTPOPERATE_H
#define HTTPOPERATE_H

#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>

class HttpOperate:public QObject
{
    
    
    Q_OBJECT
public:
    HttpOperate();
    void SendPostRequst();//用于发送Post请求的成员函数
    void SendGetRequst();//用于发生Get请求的成员函数

private:
    QNetworkAccessManager* mNetworkManager;
    QNetworkReply* mReply;

public slots: //类中做槽函数的成员函数一般写在public slots下,Qt5以及以上版本可以不写public slots
    void ReplyFinshed();
};

#endif // HTTPOPERATE_H

源文件httpoperate.cpp中的内容

#include "httpoperate.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QStringDecoder>
#include <QObject>
HttpOperate::HttpOperate() {
    
    }

void HttpOperate::SendGetRequst()
{
    
    
    mNetworkManager = new QNetworkAccessManager(this);
    QNetworkRequest _quest;
    QString url = "http://127.0.0.1:8083/v3/api/client/v1/captchaImage";
    url.append("?key1=小强&key2=xiao qing");
    _quest.setUrl((QUrl(url)));
    _quest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
    mReply = mNetworkManager->get(_quest);
    QByteArray _data = mReply->readAll();//读出数据
    //QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").toUtf8().constData();
    qInfo()<<"1_data ==> "<<_data;
    //connect(mReply,&QNetworkReply::finished,this,&HttpOperate::ReplyFinshed);//方式一
    // auto lambdaFun = [=]{ReplyFinshed();};//lambda函数
    // connect(mReply,&QNetworkReply::finished,lambdaFun);//这里的信号的接受者可以省略不写
    connect(mReply,&QNetworkReply::finished,[=]{
    
    //这里的信号的接受者可以省略不写
        ReplyFinshed();
    });
    qInfo()<<"2_data ==> " << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").toUtf8().constData();
}

void HttpOperate::SendPostRequst()
{
    
    
    mNetworkManager = new QNetworkAccessManager(this);
    QNetworkRequest _quest;
    _quest.setUrl((QUrl("http://127.0.0.1:8083/v3/api/client/v1/createSignature")));
    // _quest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
    _quest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    QJsonDocument document;
    QJsonObject obj;
    obj.insert("key1", "小明");
    obj.insert("key2", "xiao hong");
    document.setObject(obj);
    QByteArray _postData = document.toJson(QJsonDocument::Compact);//以Json字符串的方式传参
    mReply = mNetworkManager->post(_quest,_postData);
    QByteArray _data = mReply->readAll();//读出数据
    qDebug()<<"1_data ==> "<<_data;//此s时数据为空
    //connect(mReply,&QNetworkReply::finished,this,&HttpOperate::ReplyFinshed);//方式一
    // auto lambdaFun = [=]{ReplyFinshed();};//lambda函数
    // connect(mReply,&QNetworkReply::finished,this,lambdaFun);//方式二
    connect(mReply,&QNetworkReply::finished,this,[=]{
    
    
        ReplyFinshed();
    });//方式三
    qDebug()<<"2_data ==> ";
}

void HttpOperate::ReplyFinshed()
{
    
    
    if (mReply->error() == QNetworkReply::NoError)
    {
    
    
        // 处理返回的数据
        QByteArray _data = mReply->readAll();//读出数据
        auto toUtf16 = QStringDecoder(QStringDecoder::Utf8);
        QString str = toUtf16(_data);
        qInfo()<<"_data ==> "<<str;
    } else {
    
    
        // 处理错误
        qDebug()<<"error ==> "<<mReply->error();
    }
    mReply->deleteLater();
}

main.cpp中的代码:

#include <QCoreApplication>
#include "httpoperate.h"
int main(int argc, char *argv[])
{
    
    
    QCoreApplication a(argc, argv);
    HttpOperate hoper;
    hoper.SendPostRequst();//发起Post请求测试

    HttpOperate hoper1;
    hoper1.SendGetRequst();//发起Get请求测试
    return a.exec();//主程序会在这里阻塞
}

注意:When the slot function is a global function or a lambda function, the receiver of the signal can be omitted.

Get request steps

Steps:
1. Initialize the QNetworkAccessManager object.
2. Set the request URL.
3. The connection message is returned.
4. Send a GET request.
The key code above is:

/*内部发起http连接,连接成功后发起get请求.
  此接口是异步接口。请求发起后,会立即返回一个QNetworkReply类型对象的地址,
  此时打印它如上的1_data ==>结果为空字符串。
  当get请求响应返回后,会自动触发mReply所指对象的finished信号,此时mReply指对象里就有数据了,类似于Ajax的请求方式。
  然后调用响应的槽函数ReplyFinshed()处理读取数据的操作。
*/
mReply = mNetworkManager->post(_quest,_postData);
connect(mReply,&QNetworkReply::finished,this,&HttpOperate::ReplyFinshed);//将信号和槽函数进行关联,类似于绑定或注册的作用

Post request steps

Initialize the QNetworkAccessManager object.
Set the request URL.
Set the request header Header,
set the request body,
and return the connection message.
Send a POST request.

/*内部发起http连接,连接成功后发起post请求.
  此接口是异步接口。请求发起后,会立即返回一个QNetworkReply类型对象的地址,
  此时打印它如上的1_data ==>结果为空字符串。
  当get请求响应返回后,会自动触发mReply所指对象的finished信号,此时mReply指对象里就有数据了,类似于Ajax的请求方式。
  然后调用响应的槽函数ReplyFinshed()处理读取数据的操作。
*/
mReply = mNetworkManager->get(_quest);
connect(mReply,&QNetworkReply::finished,this,&HttpOperate::ReplyFinshed);//将信号和槽函数进行关联,类似于绑定或注册的作用

Test Results

The get request to test the backend service uses the springboot service.
The backend interface is:
Insert image description here
Backend printing content:
Insert image description here
QT console output content:
Insert image description here
The post request to test the backend service also uses the springboot service.
The backend interface is:
Insert image description here
Backend printing content:
Insert image description here
QT control Station output content:
Insert image description here

Guess you like

Origin blog.csdn.net/adminstate/article/details/135103533