#include "TcpResponse.h" #include 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(); }