post请求
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QObject>
#include <QEventLoop>
#include <QNetworkReply>
int httpPost(const QString& sUrl, QByteArray& outArr, const QString& strToken)
{
QByteArray data;
QNetworkRequest request(sUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json;charset=UTF-8");
if (!strToken.isEmpty())
{
request.setRawHeader("token", strToken.toLatin1());
}
auto networkManager = std::make_shared<QNetworkAccessManager>();
QNetworkReply *pReply = networkManager->post(request, data);
QEventLoop eventLoop;
QObject::connect(networkManager.get(), &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
eventLoop.exec();
outArr = pReply->readAll();
int nRet = pReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
delete pReply;
return nRet;
}
Get请求
int httpGet(const QString& sUrl, QByteArray& outArr, const QString& strToken)
{
QNetworkRequest request(sUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json;charset=UTF-8");
if (!strToken.isEmpty())
{
request.setRawHeader("token", strToken.toLatin1());
}
auto pNetAccessMgr = std::make_shared<QNetworkAccessManager>();
QNetworkReply *pReply = pNetAccessMgr->get(request);
QEventLoop eventLoop;
QObject::connect(pNetAccessMgr.get(), &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
eventLoop.exec();
outArr = pReply->readAll();
int nRet = pReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
delete pReply;
return nRet;
}
QByteArray getInfo()
{
QByteArray outArr;
QString strURL = QString("http://%1/test?param2=%2¶m3=%3")
.arg("参数1")
.arg("参数2")
.arg("参数3");
QString strToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1OTgwNTMzNzc5MTg1OTA2Mzg5IiwiaWF0IjoxNjQ1NTE4NjkyLCJ0b2tlbiI6IjRjZTcyYjhiMDJiNDQ0ZTFiYTgwNzY0NDU5MGI0OGM3In0.IRGt1uxs9rJiK9qXkQQDCv6nA1rvwxtjosUUyBGh4ZM";
httpPost(strURL, outArr, strToken );
return outArr;
}