其他分享
首页 > 其他分享> > Qt-网络应用开发初步

Qt-网络应用开发初步

作者:互联网

    通过调用服务端接口,解析返回的json数据。此例子在Qt Creator中创建   

1.  .pro文件

    在文件中添加如下语句:

QT += network

    若在VS中创建Qt项目,则在.h或.cpp文件中添加头文件"#include <QNetwork>" 即可   

2. mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>


class QNetworkAccessManager;
class QNetworkReply;

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void replyFinished(QNetworkReply* reply);

private:
    Ui::MainWindow *ui;
    QNetworkAccessManager* m_networkAccessManager;

};

#endif // MAINWINDOW_H

3. mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtNetwork>
#include <QJsonDocument>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_networkAccessManager = new QNetworkAccessManager(this);
    connect(m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    QUrl url("http://192.168.10.33:8343/FortuneApplication/GetThreadDataFromType");
    request.setUrl(url);

    QJsonObject jsonObject;
    jsonObject.insert("threadType", QJsonValue("STM6x1"));
    QJsonDocument jsonDocument;
    jsonDocument.setObject(jsonObject);
    QByteArray data = jsonDocument.toJson(QJsonDocument::Compact);
    qDebug() << "Input: " << data;

    m_networkAccessManager->post(request, data);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::replyFinished(QNetworkReply* reply)
{
    QString replyContents = reply->readAll();

    QJsonDocument jsonDocument = QJsonDocument::fromJson(replyContents.toUtf8().data());
    if(jsonDocument.isNull())
    {
        qDebug() << "please check the string" << replyContents.toUtf8().data();
        ui->textBrowser->setText(replyContents);
        reply->deleteLater();
        return;
    }

    if(jsonDocument.isObject())
    {
        QJsonObject jsonObject = jsonDocument.object();
        QStringList keys = jsonObject.keys();  //无序排列
        replyContents += "\n" + keys.join(", ");
    }

    ui->textBrowser->setText(replyContents);

    reply->deleteLater();
}

 

标签:Qt,网络应用,jsonDocument,初步,ui,reply,include,MainWindow,replyContents
来源: https://www.cnblogs.com/xiang-L/p/16034179.html