.cpp文件
详情请看代码注释
#include "customize_files/network_manager.h"
#include
#include
#include
#include
#include
std::shared_ptr NetworkManager::_instPtr{nullptr};
std::mutex NetworkManager::mutex_;
//单例模式
std::shared_ptr NetworkManager::getSingletonPtr() {
if (!_instPtr) {
std::lock_guard gLock(mutex_);
if (_instPtr == nullptr) {
_instPtr.reset(new NetworkManager, [](NetworkManager* inst) {delete inst; });
}
}
return _instPtr;
}
NetworkManager::NetworkManager(QObject* parent) {
netAccessMgr_ = std::make_shared();
}
NetworkManager::~NetworkManager() {
}
// path 对应URL,QNetworkAccessManager::Operation operation,http的三种方式pos,put,get,(还有一种,本文没写),QByteArray data对应传递的请求头,或者内容,
void NetworkManager::fetchServerData(QString path, QNetworkAccessManager::Operation operation, QByteArray data, bool sync) {
QUrl url(path);
QNetworkRequest request(url);
QNetworkReply* reply = NULL;
//request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");//application/json
if (operation == QNetworkAccessManager::GetOperation) {
reply = netAccessMgr_->get(request);
}
else if (operation == QNetworkAccessManager::PostOperation) {
reply = netAccessMgr_->post(request, data);
}
else {
reply = netAccessMgr_->put(request, data);
}
if (sync) {
// 同步
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
if (reply->error() == QNetworkReply::NoError) {
QString strReply = (QString)reply->readAll();
QJsonParseError jsonError;
QJsonDocument jsonDocument = QJsonDocument::fromJson(strReply.toUtf8(), &jsonError);
if (jsonError.error == QJsonParseError::NoError) {
emit queryServerSuccessed(reply->url().path(), jsonDocument);
}
}
else {
//Failed;
QString strReply = (QString)reply->readAll();
QJsonParseError jsonError;
QJsonDocument jsonDocument = QJsonDocument::fromJson(strReply.toUtf8(), &jsonError);
QJsonObject objs = jsonDocument.object();
QByteArray byteArray = jsonDocument.toJson(QJsonDocument::Compact);
QString strJson(byteArray);
emit errorServerSuccessed(reply->url().path(), jsonDocument);
}
}
else
{
//异步
connect(netAccessMgr_.get(), SIGNAL(finished(QNetworkReply*)), this, SLOT(handleAsyncRequestFinished(QNetworkReply*)));
}
}
//这个跟上一个一样,直接返回结果
QJsonDocument NetworkManager::receiveHttpData(QString path, QNetworkAccessManager::Operation operation, QByteArray data, bool sync)
{
QUrl url(path);
QNetworkRequest request(url);
QNetworkReply* reply = NULL;
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");//application/json
if (operation == QNetworkAccessManager::GetOperation) {
reply = netAccessMgr_->get(request);
}
else if (operation == QNetworkAccessManager::PostOperation) {
reply = netAccessMgr_->post(request, data);
}
if (sync)
{
// 同步
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
if (reply->error() == QNetworkReply::NoError) {
QString strReply = (QString)reply->readAll();
QJsonParseError jsonError;
QJsonDocument jsonDocument = QJsonDocument::fromJson(strReply.toUtf8(), &jsonError);
if (jsonError.error == QJsonParseError::NoError) {
return jsonDocument;
}
}
}
return QJsonDocument();
}
// 设置请求头的方式 使用get
QByteArray NetworkManager::getUrl(QString url, QByteArray data,int type)
{
QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager();
QNetworkRequest requestInfo;
requestInfo.setUrl(QUrl(url));
requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
requestInfo.setRawHeader(QByteArray("X-Subject-Token"), data); //设置请求头
QEventLoop eventLoop;
QNetworkReply *reply = m_pHttpMgr->get(requestInfo);;
connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
//错误处理
if (reply->error() == QNetworkReply::NoError)
{
qDebug() << "request protobufHttp NoError";
}
else
{
QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
}
//请求返回的结果
QByteArray responseByte = reply->readAll();
return responseByte;
}
//设置请求头和请求内容的方式。使用put
void NetworkManager::keepAliveVideo(QString path, QByteArray data, QString token)
{
QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager();
//设置url
QString url = path;
//设置头信息
QNetworkRequest requestInfo;
requestInfo.setUrl(QUrl(url));
requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
requestInfo.setRawHeader(QByteArray("X-Subject-Token"), data);
//发送数据
QByteArray qByteHttpData;
qByteHttpData.append(QString("{\"token\": \"%1\"}").arg(token));
QNetworkReply *reply = m_pHttpMgr->put(requestInfo, qByteHttpData);
QEventLoop eventLoop;
connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
//请求收到的结果
QByteArray responseByte = reply->readAll();
QString strReply = (QString)reply->readAll();
qWarning() << responseByte;
qWarning() << strReply;
}
void NetworkManager::handleAsyncRequestFinished(QNetworkReply* reply) {
if (reply->error() == QNetworkReply::NoError) {
QString strReply = (QString)reply->readAll();
QJsonParseError jsonError;
QJsonDocument jsonDocument = QJsonDocument::fromJson(strReply.toUtf8(), &jsonError);
if (jsonError.error == QJsonParseError::NoError) {
emit queryServerSuccessed(reply->url().path(), jsonDocument);
}
}
else {
//Failed;
}
}
.h文件
/**
*
* @brief Declares the network manager class
*/
#ifndef NETWORK_MANAGER_H
#define NETWORK_MANAGER_H
#include
#include
#include
#include
#include
#include
#include
// 线程安全的单例类(懒汉模式)
// 目前支持HTTP协议的GET, POST, 同步, 异步, 返回JSON格式数据
class NetworkManager : public QObject {
Q_OBJECT
public:
static std::shared_ptr getSingletonPtr();
NetworkManager(const NetworkManager&) = delete;
NetworkManager& operator=(const NetworkManager&) = delete;
void fetchServerData(QString path, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, QByteArray data = NULL, bool sync = true);
QJsonDocument receiveHttpData(QString path, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, QByteArray data = NULL, bool sync = true);
QByteArray getUrl(QString path, QByteArray data, int type);
void keepAliveVideo(QString path, QByteArray data,QString token);
signals:
void queryServerSuccessed(QString path, QJsonDocument& jsonDocument);
void errorServerSuccessed(QString path, QJsonDocument& jsonDocument);
void hmjqueryServerSuccessed(QString path, QJsonDocument& jsonDocument);
void hmjerrorServerSuccessed(QString path, QJsonDocument& jsonDocument);
void dataAboveServerSuccessed(QString path,QJsonDocument& jsonDocument);
void dataAboveServererror(QString path, QJsonDocument& jsonDocument);
private:
explicit NetworkManager(QObject* parent = 0);
~NetworkManager();
private slots:
void handleAsyncRequestFinished(QNetworkReply* reply);
private:
static std::shared_ptr _instPtr;
static std::mutex mutex_;
std::shared_ptr netAccessMgr_;
QNetworkAccessManager* netAccessMgr_tt;
};
#endif // !NETWORK_MANAGER_H