FemaLocalSoftware/httpclient.cpp
2024-11-28 21:34:00 +03:00

57 lines
1.9 KiB
C++

#include "httpclient.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QEventLoop>
HttpClient::HttpClient(QObject *parent)
: QObject(parent), networkManager(new QNetworkAccessManager(this)) {}
QJsonObject HttpClient::get(const QString &url) {
QNetworkRequest request{QUrl(url)};
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply *reply = networkManager->get(request);
return processReply(reply);
}
QJsonObject HttpClient::post(const QString &url, const QJsonObject &json) {
QNetworkRequest request{QUrl(url)};
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply *reply = networkManager->post(request, QJsonDocument(json).toJson());
return processReply(reply);
}
QJsonObject HttpClient::put(const QString &url, const QJsonObject &json) {
QNetworkRequest request{QUrl(url)};
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply *reply = networkManager->put(request, QJsonDocument(json).toJson());
return processReply(reply);
}
QJsonObject HttpClient::processReply(QNetworkReply *reply) {
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
QJsonObject result;
if (reply->error() == QNetworkReply::NoError) {
QByteArray responseData = reply->readAll();
QJsonParseError parseError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData, &parseError);
if (parseError.error == QJsonParseError::NoError && jsonDoc.isObject()) {
result = jsonDoc.object();
} else {
result["error"] = "Invalid JSON response.";
}
} else {
result["error"] = reply->errorString();
}
reply->deleteLater();
return result;
}