RecordControlApplication/TcpResponse.cpp

67 lines
1.4 KiB
C++
Raw Normal View History

#include "TcpResponse.h"
#include <Json.h>
TcpResponse::TcpResponse(QTcpSocket* socket)
: socket(socket)
{
}
/**
* @brief url
* @param url
*/
void TcpResponse::setUrl(const QString& url)
{
this->url = url;
}
/**
* @brief
*/
void TcpResponse::success(QString msg, QVariant data)
{
QByteArray respone;
// 请求路径
respone += QString("Url: %1\r\n").arg(url).toUtf8();
// 响应数据
QVariantMap map;
map["status"] = "success";
map["msg"] = msg.isEmpty() ? "响应成功" : msg;
map["data"] = data.isNull() ? "" : data;
QByteArray byteData = Json::encode(map).toUtf8();
int length = byteData.length();
// 响应体长度
respone += QString("Content-Length: %1\r\n\r\n").arg(length).toUtf8();
respone += byteData;
socket->write(respone);
socket->flush();
}
/**
* @brief
*/
void TcpResponse::error(QString msg)
{
QByteArray respone;
// 请求路径
respone += QString("Url: %1\r\n").arg(url).toUtf8();
// 响应数据
QVariantMap map;
map["status"] = "error";
map["msg"] = msg.isEmpty() ? "响应失败" : msg;
map["data"] = "";
// 打包成json格式
QByteArray byteData = Json::encode(map).toUtf8();
int length = byteData.length();
// 响应体长度
respone += QString("Content-Length: %1\r\n\r\n").arg(length).toUtf8();
respone += byteData;
socket->write(respone);
socket->flush();
}