RecordControlApplication/TcpRequest.cpp

74 lines
1.8 KiB
C++
Raw Permalink Normal View History

#include "TcpRequest.h"
#include "Log.h"
#include <Json.h>
QString TcpRequest::getUrl()
{
return url;
}
/**
* @brief
*/
QVariantMap TcpRequest::getBodyParams()
{
QVariantMap params = this->parseParams();
return params;
}
QString TcpRequest::getErrorString()
{
return errorString;
}
/**
* @brief
*/
bool TcpRequest::readFromSocket(QTcpSocket* socket)
{
// 读取第一行
QString str = socket->readLine().trimmed();
if (!str.contains("Url: ")) {
Log::error(QString("receive error headers: %1").arg(str).toStdString());
socket->readAll();
socket->flush();
errorString = "未知请求路径参数:" + str;
return false;
} else {
url = str.split(": ")[1];
}
// 读取第二行
str = socket->readLine().trimmed();
if (!str.contains("Content-Length: ")) {
contentLength = 0;
} else {
contentLength = str.split(": ")[1].toLongLong();
}
// 如果请求体长度为0就不再往下读取
if (contentLength == 0) {
socket->readAll();
socket->flush();
return true;
} else {
body.clear();
// 读取空行并丢弃
socket->readLine();
// 循环读取数据直到读取了content-length长度数据
qint64 readSize = 0;
while (socket->bytesAvailable() > 0) {
char bytes[contentLength];
qint64 size = socket->read(bytes, contentLength - readSize);
if (size == -1) {
errorString = "socket读取数据出错";
return false;
}
readSize += size;
body += QString::fromLocal8Bit(bytes, size);
if (readSize >= contentLength) {
break;
}
}
}
return true;
}