#include "httpclient.h" #include #include #include #include #include #include #include #include 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; }