-
Notifications
You must be signed in to change notification settings - Fork 1
/
apirequest.cpp
46 lines (44 loc) · 2.05 KB
/
apirequest.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "apirequest.h"
ApiResponse ApiRequest::get(const QString &path) {
QNetworkRequest request(QUrl(baseUrl + path));
QNetworkReply* reply = manager->get(request);
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
qDebug()<<reply->error();
if (reply->error() == QNetworkReply::NoError||reply->error()>200&&reply->error()<300) {
QByteArray responseData = reply->readAll();
ApiResponse response(responseData);
return response;
} else {
qDebug() << "Error:" << reply->errorString();
QString jsonString = R"({"code": 666, "message": "ApiRequest error!", "data": "Nooo!"})";
QByteArray jsonData = jsonString.toUtf8();
QJsonDocument document = QJsonDocument::fromJson(jsonData);
QJsonObject jsonObject = document.object();
ApiResponse errorResponse(666,"ApiRequest error!",jsonObject,jsonObject.value("data"));
return errorResponse;
}
}
ApiResponse ApiRequest::post(const QString &path, const QByteArray &data) {
QNetworkRequest request(QUrl(baseUrl + path));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QNetworkReply* reply = manager->post(request, data);
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
qDebug()<<reply->error();
if (reply->error() == QNetworkReply::NoError||reply->error()>200&&reply->error()<300 ){
QByteArray responseData = reply->readAll();
ApiResponse response(responseData);
return response;
} else {
qDebug() << "Error:" << reply->errorString();
QString jsonString = R"({"code": 666, "message": "ApiRequest error!", "data": "Nooo!"})";
QByteArray jsonData = jsonString.toUtf8();
QJsonDocument document = QJsonDocument::fromJson(jsonData);
QJsonObject jsonObject = document.object();
ApiResponse errorResponse(666,"ApiRequest error!",jsonObject,jsonObject.value("data"));
return errorResponse;
}
}