C++ QT框架QNetworkAccessManager,Request HTTP请求模块

json对象构建

实例 创建一个对象
QJsonObject::QJsonObject()

将键值对添加到QJsonObject对象中
QJsonObject::iterator insert(const QString &key,const QJsonValue &value);

//构建json对象
#include 
#include 
#include 



QJsonObject rootObj;
rootObj.insert("name","lieli");

//构建数组
QJsonArray provinceArray;
QJsonObject sdObj;

dObj.insert("phone","19991111111");
sdObj.insert("emint","[email protected]");
provinceArray.append(sdObj);
rootObj.insert("provinces",provinceArray);
QJsonDocument doc(rootObj);
QByteArray json = doc.toJson();

//qDebug
 {
      "name":"lilei",
      "provinces": [
            {
                "emint": "[email protected]",
                "phone": "19991111111"
            }
        ]
  }

在.h 头文件写入

#include 

protected:
    void getWeatherInfo();//发请求的http

private:
    QNetworkAccessManager* mNetAccessMsg;

在.cpp文件开始写

void MainWindow::getWeatherInfo()
{
    QJsonObject body; //构建json 对象用来装请求携带的参数
    QString phones = ui->phone->text();
    QString upwd = ui->upwd->text();

    //非空校验,有条件可以匹配正则校验
    if(phones.isEmpty() || upwd.isEmpty()){
        QMessageBox::warning(this,"title","手机号或密码不能为空",QMessageBox::Ok);
    }

    body.insert("phone",phones);

    body.insert("upwd",upwd);
    QByteArray postData;
    postData.append(QJsonDocument(body).toJson());

    QUrl url("http://你的接口地址/api/phone/login");
    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");//header请求头
    request.setUrl(url);
    mNetAccessMsg->post(request, postData);  //发起post 请求

}

C++ QT框架QNetworkAccessManager,Request HTTP请求模块_第1张图片C++ QT框架QNetworkAccessManager,Request HTTP请求模块_第2张图片

你可能感兴趣的:(c++,qt,开发语言)