一、头文件
#ifndef ABSHTTP_H
#define ABSHTTP_H
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QEventLoop>
#include "httpresult.h"
#define EHM_IP QString("http://kingzyl.top:7002")
class Http : public QObject
{
Q_OBJECT
public:
explicit Http(QObject *parent = nullptr);
void httpGet(QUrl sUrl);
void httpGet(QUrl sUrl, QString headerName, QString headerValue);
void httpPost(QUrl sUrl, QMap<QString,QString> map_data, QMap<QString,QString> map_head);
void httpPost(QUrl sUrl, QByteArray jsonArray, QString headerName, QString headerValue);
private:
void onReplyFinished();
signals:
void signalReplyFinished(HttpResult res);
private:
QString m_sProtocol;
QString m_sIp;
QString m_sPort;
QString m_sPath;
QNetworkReply *m_pReply = Q_NULLPTR;
QNetworkAccessManager m_manager;
QEventLoop temp_loop;
QUrl m_url;
};
#endif // ABSHTTP_H
二、CPP
1. Get请求
void Http::httpGet(QUrl sUrl)
{
QNetworkRequest request;
request.setUrl(sUrl);
if(m_pReply != Q_NULLPTR) {//更改reply指向位置钱一定要保证之前的定义了自动delete
m_pReply->deleteLater();
}
m_pReply = m_manager.get(request);
qDebug() << "start get";
connect(m_pReply, &QNetworkReply::finished, this, &Http::onReplyFinished, Qt::QueuedConnection);
temp_loop.exec();
}
2.post请求
void Http::httpPost(QUrl sUrl, QMap<QString, QString> map_data, QMap<QString, QString> map_head)
{
m_url = sUrl;
QNetworkRequest request;
QMap<QString,QString>::iterator it_data = map_data.begin();
QString sData;
while (it_data != map_data.end()) {
if(sData.isEmpty())
{
sData = QString("%1=%2").arg(it_data.key()).arg(it_data.value());
}
else
{
sData = QString("&%1=%2").arg(it_data.key()).arg(it_data.value());
}
it_data++;
}
QByteArray httpData = sData.toUtf8();
QMap<QString,QString>::iterator it_head = map_head.begin();
while (it_head != map_head.end()) {
request.setRawHeader(it_head.key().toUtf8(), it_head.value().toUtf8());
it_head++;
}
request.setUrl(sUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
if(m_pReply != Q_NULLPTR) {//更改reply指向位置钱一定要保证之前的定义了自动delete
m_pReply->deleteLater();
}
m_pReply = m_manager.post(request, httpData);
qDebug() << "start post";
connect(m_pReply, &QNetworkReply::finished, this, &Http::onReplyFinished, Qt::QueuedConnection);
temp_loop.exec();
}