FemaLocalSoftware/httpclient.cpp
lopata29435_NSK bb95803fbd fix(1)
2025-01-10 01:42:34 +07:00

81 lines
2.8 KiB
C++

#include "httpclient.h"
#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QCoreApplication>
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::post(const QString &url)
{
QNetworkRequest request{QUrl(url)};
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply *reply = networkManager->post(request, "");
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.";
QMessageBox::critical(nullptr, "Ошибка", "Получен неверный формат ответа от сервера.");
}
} else {
result["error"] = reply->errorString();
if (result["error"].toString().contains("Service Unavailable") || result["error"].toString().contains("Connection refused") || result["error"].toString().contains("not found")) {
throw std::runtime_error("Сервер недоступен. Приложение будет закрыто");
}
QMessageBox::critical(nullptr, "Ошибка", "Ошибка при запросе: " + reply->errorString());
}
reply->deleteLater();
return result;
}