httpreq.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "httpreq.h"
  2. #include "maindlg.h"
  3. #include <QMessageBox>
  4. HttpReq::HttpReq(QObject *parent)
  5. : QObject{parent}
  6. {
  7. m_pMainDlg = static_cast<MainDlg *>(parent); // 保存主窗口指针
  8. init();
  9. }
  10. // 模块初始化
  11. void HttpReq::init()
  12. {
  13. m_pNetworkManager = new QNetworkAccessManager(this);
  14. return;
  15. }
  16. // 配置网络参数
  17. quint8 HttpReq::configNetworkParam(QString strHostAddress, QString strPort)
  18. {
  19. // 参数容错处理
  20. if (strHostAddress.length() <= 0 || strPort.length() <= 0)
  21. {
  22. return 1;
  23. }
  24. // 保存网络基地址参数
  25. m_strBaseUrl = strHostAddress + ":" + strPort + "/pcapi/bparam/";
  26. return 0;
  27. }
  28. // 发送post请求
  29. // strApiName:API接口
  30. // jsonObject:json格式的数据
  31. // 返回值,字符串
  32. QString HttpReq::sendPostReq(QString strApiName, QJsonObject jsonObject)
  33. {
  34. QString strBaseUrl = "";
  35. QNetworkReply *reply = NULL;
  36. QEventLoop loop; // 创建一个局部事件循环
  37. // 组织网络地址
  38. if (strApiName.length() <= 0)
  39. {
  40. return QString();
  41. }
  42. // 网络地址
  43. // strBaseUrl = "https://" + m_strBaseUrl + strApiName;
  44. strBaseUrl = m_strBaseUrl + strApiName;
  45. QUrl hostUrl(strBaseUrl);
  46. QNetworkRequest request(hostUrl);
  47. // 设置请求头
  48. request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  49. // 将json数据转成QByteArray数据
  50. QJsonDocument jsonDoc(jsonObject);
  51. QByteArray jsonData = jsonDoc.toJson();
  52. // 发送post请求,并等待返回
  53. reply = m_pNetworkManager->post(request, jsonData);
  54. // 将reply的finished信号连接到事件循环的quit槽,以便在请求完成时退出循环
  55. QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
  56. // 执行事件循环,直到finished信号被触发
  57. loop.exec();
  58. // 检查返回结果
  59. if (reply->error() == QNetworkReply::NoError)
  60. {
  61. return QString::fromUtf8(reply->readAll());
  62. // return QString("上传数据成功");
  63. }
  64. else
  65. {
  66. return QString("上传数据失败");
  67. }
  68. }