- .h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtNetwork>
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void replyFinished();
private slots:
void on_pushButton_clicked();
private:
Ui::Widget *ui;
QNetworkAccessManager *manager;
QNetworkRequest request;
QNetworkReply *reply;
};
#endif // WIDGET_H
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- .cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished,this, &Widget::replyFinished);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
request = QNetworkRequest(QUrl("http://127.0.0.1:9090/api/getUserInfo"));
reply = manager->get(request);
}
void Widget::replyFinished() {
if (reply->error() == QNetworkReply::NoError) {
QByteArray data = reply->readAll();
qDebug() << data;
QJsonDocument document;
QJsonParseError error;
QJsonObject rootObject = QJsonDocument::fromJson(data, &error).object();
qDebug() << rootObject;
QJsonObject _data = rootObject["data"].toObject();
QString username = _data["username"].toString();
int age = _data["age"].toInt();
QString job = _data["job"].toString();
QString result = QString("User Info: name: %1, age %2, job is %3").arg(username).arg(age).arg(job);
qDebug() << result;
} else {
qDebug() << "Error:" << reply->errorString();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.