KShare/io/ioutils.cpp

60 lines
2.3 KiB
C++
Raw Normal View History

2017-04-23 15:05:48 +02:00
#include "ioutils.hpp"
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
2017-05-06 13:21:12 +02:00
namespace ioutils {
2017-04-23 15:05:48 +02:00
QNetworkAccessManager networkManager;
}
void ioutils::getJson(QUrl target, QList<QPair<QString, QString>> headers, std::function<void(QJsonDocument, QByteArray, QNetworkReply *)> callback) {
QNetworkRequest req(target);
for (auto header : headers) {
req.setRawHeader(header.first.toUtf8(), header.second.toUtf8());
}
QNetworkReply *reply = networkManager.get(req);
QObject::connect(reply, &QNetworkReply::finished, [reply, callback] {
2017-05-13 22:39:05 +02:00
QByteArray data = reply->readAll();
callback(QJsonDocument::fromJson(data), data, reply);
reply->deleteLater();
});
2017-04-23 15:05:48 +02:00
}
void ioutils::postJson(QUrl target, QList<QPair<QString, QString>> headers, QByteArray body, std::function<void(QJsonDocument, QByteArray, QNetworkReply *)> callback) {
QNetworkRequest req(target);
for (auto header : headers) {
req.setRawHeader(header.first.toUtf8(), header.second.toUtf8());
}
QNetworkReply *reply = networkManager.post(req, body);
QObject::connect(reply, &QNetworkReply::finished, [reply, callback] {
2017-05-13 22:39:05 +02:00
QByteArray data = reply->readAll();
callback(QJsonDocument::fromJson(data), data, reply);
delete reply;
});
2017-04-24 23:14:01 +02:00
}
void ioutils::getData(QUrl target, QList<QPair<QString, QString>> headers, std::function<void(QByteArray, QNetworkReply *)> callback) {
QNetworkRequest req(target);
for (auto header : headers) {
req.setRawHeader(header.first.toUtf8(), header.second.toUtf8());
}
QNetworkReply *reply = networkManager.get(req);
QObject::connect(reply, &QNetworkReply::finished, [reply, callback] {
callback(reply->readAll(), reply);
delete reply;
});
2017-04-24 23:14:01 +02:00
}
void ioutils::postData(QUrl target, QList<QPair<QString, QString>> headers, QByteArray body, std::function<void(QByteArray, QNetworkReply *)> callback) {
QNetworkRequest req(target);
for (auto header : headers) {
req.setRawHeader(header.first.toUtf8(), header.second.toUtf8());
}
QNetworkReply *reply = networkManager.post(req, body);
QObject::connect(reply, &QNetworkReply::finished, [reply, callback] {
callback(reply->readAll(), reply);
delete reply;
});
2017-04-23 15:05:48 +02:00
}