首先要在.pro文件中加上QT += network
。
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void run();
void fun();
void funBack(QNetworkReply* reply);
QString CmdParse(QJsonValue value);
private:
Ui::MainWindow *ui;
private:
QNetworkAccessManager *manager;
QString data;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
#include
#include
#include
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//调用函数发送请求,参数是请求的服务器地址
run();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::run(){
fun();
}
//请求
void MainWindow::fun(){
manager = new QNetworkAccessManager(this);
//通信完成后,自动执行funBack
connect(manager,&QNetworkAccessManager::finished,this,&MainWindow::funBack);
// Json数据,请求体
QJsonObject json;
json.insert("xxx", "xxxx");
json.insert("xxxx", "xxxxxxxxx");
QJsonDocument document;
document.setObject(json);
QByteArray dataArray = document.toJson(QJsonDocument::Compact);
// 构造请求
QNetworkRequest request;
request.setUrl(QUrl("xxxxx:xxxxxxxx/xxxx/xxx"));
//构造请求头
request.setRawHeader("User-Agent","xxxx");
request.setRawHeader("Content-Type","application/json");
request.setRawHeader("Host","xxxxxxxxxxx");
request.setRawHeader("Connection", "keep-alive");
// 发送请求
manager->post(request, dataArray);
}
//接收响应
void MainWindow::funBack(QNetworkReply* reply){
// 获取响应信息
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug() << "statusCode:" << statusCode;
QByteArray bytes = reply->readAll();
//qDebug()<
QJsonParseError jsonError;
QJsonDocument doucment = QJsonDocument::fromJson(bytes, &jsonError);
if (jsonError.error != QJsonParseError::NoError) {
qDebug() << QStringLiteral("parse Json error!");
return;
}else qDebug() << QStringLiteral("parse Json success!");
// 解析Json
if (doucment.isObject())
{
QJsonObject obj = doucment.object();
QJsonValue value;
if (obj.contains("data"))
{
QJsonValue value = obj.value("data");
//嵌套解析json数据
data = CmdParse(value);
qDebug()<<data;
}
}
}
//嵌套解析json
QString MainWindow::CmdParse(QJsonValue value)
{
QString dataValue; //容器保存json值
if (value.isObject()) //判断第二级对象是否存在
{
QJsonObject obj = value.toObject();
//abcxxx是json嵌套里面的
if (obj.contains("abcxxx"))
{
QJsonValue value = obj.value("abc");
if(value.isString()){
dataValue=value.toString();
}else{
qDebug()<<value.toString();
}
}
}
return dataValue; //返回解析好的json值
}
#include "mainwindow.h"
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}