QT += network
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QWidget> #include <QObject> #include <QDebug> #include <QHttpMultiPart> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QMetaObject> #include <QEventLoop> #include <QJsonDocument> //以下是json数据传送所需头文件 #include <QJsonParseError> #include <QJsonObject> #include <QJsonValue> #include <QJsonArray> 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 finishedSlot(QNetworkReply*); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QSslSocket> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); qDebug()<< QSslSocket::sslLibraryBuildVersionString(); QNetworkAccessManager * net_mgr = new QNetworkAccessManager(this); connect(net_mgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*))); QNetworkRequest net_request; net_request.setUrl(QUrl("https://saas-0-core.0.cn/v1/fn_saas_core/req_rpc_cmd")); // 下边这行也很重要,要发送json格式的数据必须要在header里设置,不然不会成功的 net_request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); QJsonObject object; object.insert("cmd", "req_get_machine_info_iot_base_bu_mid"); QJsonObject object2; object2.insert("mid", 9109513); object.insert("data", object2); QJsonDocument document=QJsonDocument(object); // 这里要将json格式的数据转换为QByteArray才行 QByteArray post_data = document.toJson(QJsonDocument::Compact); net_mgr->post(net_request, post_data); } void MainWindow::finishedSlot(QNetworkReply* reply) { if (reply->error() == QNetworkReply::NoError) { QByteArray bytes = reply->readAll(); // 下边我们将收到的body部分解析为json格式,其中有个key是status QJsonDocument jsonDocument = QJsonDocument::fromJson(bytes); qDebug()<<jsonDocument; QJsonObject jsonObject = jsonDocument.object().find("data").value().toObject(); QString value = jsonObject["productKey"].toString(); qDebug()<<"PID:"<<value; } reply->deleteLater(); } MainWindow::~MainWindow() { delete ui; }
标签:http,QT,QNetworkReply,ui,post,include,MainWindow From: https://www.cnblogs.com/ahuo/p/17475440.html