The article directories
- 0 background
- 1 Send data in JSON format
-
- 1.1 Post request class:
- 1.1 Using the POST Request class
- 2 Send JSON data
- 3 Parse THE JSON data
- 4 throw in
0 background
Since the project requires a lot of POST requests, I searched a lot of data and added my own practice to conclude this article. I wrote that beforeArticles on the same topic, but the method is troublesome, need to call json format data to carry out the POST request, this article is the above optimization. Here are some useful software and urls for post requests,
Software: the Postman
Json data parsing url
1 Send data in JSON format
1.1 Post request class:
In the Pro file, add
QT += network # networkCopy the code
.h
#ifndef HTTPNETWORKREQUEST_H
#define HTTPNETWORKREQUEST_H
#include<QNetworkAccessManager>
#include<QNetworkRequest>
#include<QString>
#include<QObject>
#include<QJsonObject>
#include<QByteArray>
class HttpNetworkRequest : public QObject
{
Q_OBJECT
public:
HttpNetworkRequest(a); ~HttpNetworkRequest(a);private:
// The type of post to perform
int m_executePostRequestType = 0;
// Parse the post type
int m_analysisPostRequestType = 0;
private:
//post Request status
enum PostStatus{
SucceedDeal = 0.// Successfully processed
ServerMaintenanceError = 1.// Server maintenance status
SeverDisconnectError = 2.// The network is disconnected
NoPermissionError = 3.// No permissions
DataAbnormalError = 4.// Json data exception error
DealDatabaseError = 5// Handle database exception errors
};
// The IP header of the request
QString m_requestIPHead = "https://baidu.com";
// Parse the post type
enum AnalysisPostType{
TestRequest = 0.// Work mode
};
// The type of post to perform
enum ExecutePostType{
TestOperate = 0.// Buy the goods
};
// Get the token of the header
QString m_accessToken;
// Send network requests and receive replies
QNetworkAccessManager* m_networkAccessManager;
// Request message problem
QNetworkRequest m_httpRequest;
// Send data
QByteArray m_sendJsonData;
/ * * * * * * * * * * * * * * request * * * * * * * * * * * * * * * * * * * * * * /
/** * @brief test post request */
void testHttpRequestPost(a);
/ * * * * * * * * * * * * * * deal with * * * * * * * * * * * * * * * * * * * * * * /
/** * @brief Processes server status requests * @param jsonObject */
bool dealTestRequest(QJsonObject& jsonObject);
private slots:
/** * @brief The main interface for processing the data sent back by post requests * @param reply */
void dealNetworkFinisheded(QNetworkReply *reply);
// Call a unique interface
public slots:
/** * @brief Indicates the POST type of the request operation */
void receivePostRequestType(int instruct, const QByteArray& content = "");
signals:
/** * @brief Result of processing data * @param type: interface type * Handle post parameters, various exceptions */
void sendDealDataResult(int result, int type);
};
#endif // HTTPNETWORKREQUEST_H
Copy the code
.cpp
#include "httpnetworkrequest.h"
#include<QJsonObject>
#include<QJsonDocument>
#include<QJsonArray>
#include<QNetworkReply>
#include<QDebug>
#include<QVector>
#include<QDateTime>
/* Message synchronization logic: ReceivePostRequestType -->workModeQueryRequestPost [sendServerMaintainStatus signal] -- - > accessTokenHttpRequestPost - > dealTokenReques (depending on the type of m_executePostRequestType are different, perform different operations) * /
HttpNetworkRequest::HttpNetworkRequest()
{
m_networkAccessManager = new QNetworkAccessManager(a);// Process all POST requests
connect(m_networkAccessManager, &QNetworkAccessManager::finished,
this, &HttpNetworkRequest::dealNetworkFinisheded);
}
HttpNetworkRequest::~HttpNetworkRequest()
{
qDebug() < <"HttpNetworkRequest";
delete m_networkAccessManager;
}
// Send a POST request
void HttpNetworkRequest::testHttpRequestPost(a)
{
qDebug() < <"testHttpRequestPost";
// QJsonObject obj;
// obj.insert("accountId", "1");
// QJsonDocument jsonDoc(obj);//QJsonObject转QJsonDocument
// QString str = QString(jsonDoc.toJson());//QJsonDocument转QString
// QByteArray content = str.toUtf8();
// int contentLength = content.length();
m_httpRequest.setUrl(QUrl(m_requestIPHead + "/api/clientversion/client/working/mode/query"));
m_httpRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
m_httpRequest.setRawHeader("access_token", m_accessToken.toUtf8());
m_httpRequest.setHeader(QNetworkRequest::ContentLengthHeader, m_sendJsonData.length());
m_analysisPostRequestType = AnalysisPostType::TestRequest;
// Send parameters // Send the user name and password to the Web server for authentication
m_networkAccessManager->post(m_httpRequest, m_sendJsonData);
}
// Process the POST request
bool HttpNetworkRequest::dealTestRequest(QJsonObject &jsonObject)
{
qDebug() < <"dealTestRequest:"<<jsonObject;
if(jsonObject.contains("code")) {if(jsonObject.value("code").toInt() = =200) {// Send the processing result
emit sendDealDataResult(PostStatus::SucceedDeal, m_executePostRequestType);
return true;
}else{
emit sendDealDataResult(PostStatus::DataAbnormalError, m_executePostRequestType);
return false; }}else{
emit sendDealDataResult(PostStatus::DealDatabaseError, m_executePostRequestType);
return false; }}// Post handles the total entry
void HttpNetworkRequest::dealNetworkFinisheded(QNetworkReply *reply)
{
// if(QSslSocket::supportsSsl() == true){
/ / qDebug () < < "support SSL:" < < QSslSocket: : sslLibraryBuildVersionString () + QSslSocket: : sslLibraryVersionString ();
// }else{
/ / qDebug () < < "does not support SSL:" < < QSslSocket: : sslLibraryBuildVersionString () + QSslSocket: : sslLibraryVersionString ();
/ /}
QVariant data = reply->readAll(a);// Read all data
QJsonParseError jsonError;
QJsonDocument document = QJsonDocument::fromJson(data.toByteArray(), &jsonError);
if(! document.isNull() && (jsonError.error == QJsonParseError::NoError)) {
qDebug() < <"No parsing error occurred";
qDebug() < <"JSON document as object";
QJsonObject object = document.object(a);// Convert to object
if (document.isObject()) {
switch (m_analysisPostRequestType) {
case AnalysisPostType::TestRequest:
dealTestRequest(object);
break;
default:
break; }}else{
emit sendDealDataResult(PostStatus::DealDatabaseError, m_executePostRequestType); }}else{
if(document.isNull() = =true) {qDebug() < <"document.isNull:" + reply->errorString(a);emit sendDealDataResult(PostStatus::SeverDisconnectError, m_executePostRequestType);
}else if(jsonError.error == QJsonParseError::NoError){
qDebug() < <"jsonError.error:" + reply->errorString(a);emit sendDealDataResult(PostStatus::SeverDisconnectError, m_executePostRequestType); }}// Delete the object
reply->deleteLater(a); }/ / class interface
void HttpNetworkRequest::receivePostRequestType(int instruct, const QByteArray& content){
// Get the command to execute
m_executePostRequestType = instruct;
// Get the content sent
m_sendJsonData = content;
switch (m_executePostRequestType) {
case ExecutePostType::TestOperate:
testHttpRequestPost(a);break;
default:
break; }}Copy the code
1.1 Using the POST Request class
Add the post request member to the class:
#ifndef MAININTERFACE_H
#define MAININTERFACE_H
#include <QMainWindow>
#include"httpnetworkrequest.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainInterface; }
QT_END_NAMESPACE
class MainInterface : public QMainWindow
{
Q_OBJECT
public:
MainInterface(QWidget *parent = nullptr);
~MainInterface(a);private:
Ui::MainInterface *ui;
private:
// The type of post to perform
enum ExecutePostType{
TestOperate = 0.// Buy the goods
};
/ / post request
HttpNetworkRequest* m_httpNetworkRequest;
/** * @brief testPost: Call the post method */
void testPost(a);
};
#endif // MAININTERFACE_H
Copy the code
.cpp
Call method:
#include "maininterface.h"
#include "ui_maininterface.h"
#include<QJsonDocument>
MainInterface::MainInterface(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainInterface)
{
ui->setupUi(this);
// Create an object
m_httpNetworkRequest = new HttpNetworkRequest;
testPost(a); } MainInterface::~MainInterface()
{
// Destroy the object
delete m_httpNetworkRequest;
delete ui;
}
// Send a POST request
void MainInterface::testPost(a)
{
// Json data to send
QJsonObject obj;
obj.insert("accountId"."1");
QJsonDocument jsonDoc(obj);/ / QJsonObject QJsonDocument
QString str = QString(jsonDoc.toJson());/ / QJsonDocument QString
QByteArray content = str.toUtf8(a);// Send a POST request
m_httpNetworkRequest->receivePostRequestType(ExecutePostType::TestOperate, content);
}
Copy the code
2 Send JSON data
For example, the following data:
Methods:
// Json data to send
QJsonObject sendJsonData;
sendJsonData.insert("code".200);
//加入array
QJsonArray arry;
QJsonObject tempObject1;
tempObject1.insert("name"."Xiao Ming");
tempObject1.insert("height".180);
tempObject1.insert("weight".70.3);
arry.append(tempObject1);
QJsonObject tempObject2;
tempObject2.insert("name"."Flower");
tempObject2.insert("height".165);
tempObject2.insert("weight".45.8);
arry.append(tempObject2);
sendJsonData.insert("people".QJsonValue(arry));
//加入object
QJsonObject tempObject;
tempObject.insert("school"."Carnegie Mellon University");
tempObject.insert("location"."PIT");
sendJsonData.insert("affiliation".QJsonValue(tempObject));
m_jsonData = sendJsonData;//m_jsonData is a class member variable of type QJsonObject
qDebug() < <"sendJsonData:"<<sendJsonData;
Copy the code
Handle the result returned by post:
// Process the result returned by post
connect(m_httpNetworkRequest, &HttpNetworkRequest::sendDealDataResult,
this, [and] (int result, int type){
});
Copy the code
3 Parse THE JSON data
For example, parsing the JSON data in the above example:
/ / parsing code
if(m_jsonData.contains("code")) {qDebug() < <"code:"<<m_jsonData.value("code").toInt(a); }//解析array
if(m_jsonData.contains("people")){
QJsonValue peopleObject = m_jsonData.take("people");
if(peopleObject.isArray()){
QJsonArray peopleArray = peopleObject.toArray(a);for(int i = 0; i < peopleArray.size(a); ++i){ QJsonValue value = peopleArray.at(i);
qDebug() < <"name:"<<value["name"].toString(a);qDebug() < <"height:"<<value["height"].toInt(a);qDebug() < <"weight:"<<value["weight"].toDouble(a); }}}/ / parsing obect
if(m_jsonData.contains("affiliation")){
QJsonValue affiliationValue = m_jsonData.value("affiliation");
QJsonObject affiliationObject = affiliationValue.toObject(a);if(affiliationObject.contains("school")) {qDebug() < <"school:"<<affiliationObject.value("school").toString(a);qDebug() < <"location:"<<affiliationObject.value("location").toString();
}
}
Copy the code
4 throw in
Github code cloud address CSDN resources (have integral can support, thank you)