FemaLocalSoftware/httpclient.cpp

63 lines
1.9 KiB
C++
Raw Normal View History

2024-11-28 18:34:00 +00:00
#include "httpclient.h"
#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonParseError>
2024-11-28 18:34:00 +00:00
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
HttpClient::HttpClient(QObject *parent)
: QObject(parent)
, networkManager(new QNetworkAccessManager(this))
{}
2024-11-28 18:34:00 +00:00
QJsonObject HttpClient::get(const QString &url)
{
2024-11-28 18:34:00 +00:00
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)
{
2024-11-28 18:34:00 +00:00
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)
{
2024-11-28 18:34:00 +00:00
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)
{
2024-11-28 18:34:00 +00:00
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;
}