1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #include "httpreq.h"
- #include "maindlg.h"
- #include <QMessageBox>
- HttpReq::HttpReq(QObject *parent)
- : QObject{parent}
- {
- m_pMainDlg = static_cast<MainDlg *>(parent); // 保存主窗口指针
- init();
- }
- // 模块初始化
- void HttpReq::init()
- {
- m_pNetworkManager = new QNetworkAccessManager(this);
- return;
- }
- // 配置网络参数
- quint8 HttpReq::configNetworkParam(QString strHostAddress, QString strPort)
- {
- // 参数容错处理
- if (strHostAddress.length() <= 0 || strPort.length() <= 0)
- {
- return 1;
- }
- // 保存网络基地址参数
- m_strBaseUrl = strHostAddress + ":" + strPort + "/pcapi/bparam/";
- return 0;
- }
- // 发送post请求
- // strApiName:API接口
- // jsonObject:json格式的数据
- // 返回值,字符串
- QString HttpReq::sendPostReq(QString strApiName, QJsonObject jsonObject)
- {
- QString strBaseUrl = "";
- QNetworkReply *reply = NULL;
- QEventLoop loop; // 创建一个局部事件循环
- // 组织网络地址
- if (strApiName.length() <= 0)
- {
- return QString();
- }
- // 网络地址
- // strBaseUrl = "https://" + m_strBaseUrl + strApiName;
- strBaseUrl = m_strBaseUrl + strApiName;
- QUrl hostUrl(strBaseUrl);
- QNetworkRequest request(hostUrl);
- // 设置请求头
- request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
- // 将json数据转成QByteArray数据
- QJsonDocument jsonDoc(jsonObject);
- QByteArray jsonData = jsonDoc.toJson();
- // 发送post请求,并等待返回
- reply = m_pNetworkManager->post(request, jsonData);
- // 将reply的finished信号连接到事件循环的quit槽,以便在请求完成时退出循环
- QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
- // 执行事件循环,直到finished信号被触发
- loop.exec();
- // 检查返回结果
- if (reply->error() == QNetworkReply::NoError)
- {
- return QString::fromUtf8(reply->readAll());
- // return QString("上传数据成功");
- }
- else
- {
- return QString("上传数据失败");
- }
- }
|