Skip to content

Commit

Permalink
[messenger] Add get request. Closed #98
Browse files Browse the repository at this point in the history
  • Loading branch information
alex13sh committed Aug 7, 2020
1 parent 858564f commit 26f7ddf
Showing 1 changed file with 23 additions and 12 deletions.
35 changes: 23 additions & 12 deletions application/src/requester.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrlQuery>

#include "uuidmanager.h"
#include "serializer.h"
Expand Down Expand Up @@ -58,29 +59,39 @@ QNetworkRequest Requester::createRequest(const Requester::ApiType &api)

void Requester::sendRequest(const Requester::RequestType type, const Requester::ApiType api, const QVariantMap &jsonData)
{
QNetworkRequest request = createRequest(api);
QNetworkReply *reply;
switch (type) {
case POST: {
QNetworkRequest request = createRequest(api);
QJsonObject obj = QJsonObject::fromVariantMap(jsonData);
QJsonDocument doc(obj);
QByteArray postDataByteArray = doc.toJson();

QNetworkReply *reply;
reply = m_manager->post(request, postDataByteArray);
connect(reply, &QNetworkReply::finished, [=](){
if (reply->error() == QNetworkReply::NoError) {
emit replied(urlToApi(reply->url()), reply->readAll());
} else {
emit error(statusCodeToError(
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()
));
}
});
break;
}
case GET: {
QUrlQuery params;
for (auto itr = jsonData.begin(); itr!=jsonData.end(); ++itr)
params.addQueryItem(itr.key(), itr.value().toString());
auto url = request.url();
url.setQuery(params);
request.setUrl(url);
reply = m_manager->get(request);
break;
}
default:
return;
}

connect(reply, &QNetworkReply::finished, [=]() {
if (reply->error() == QNetworkReply::NoError) {
emit replied(urlToApi(reply->url()), reply->readAll());
} else {
emit error(statusCodeToError(
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()
));
}
});
}

Requester::RequestError Requester::statusCodeToError(int code)
Expand Down

0 comments on commit 26f7ddf

Please sign in to comment.