include vk include mainwindow include QNetworkAccessManage include QNe

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "vk.h"
#include "mainwindow.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QObject>
VK::VK(QString token) {
this->token = token;
}
VK::~VK() {
}
void VK::request(QString method, std::map<QString, QString> data) {
QNetworkAccessManager *manager = new QNetworkAccessManager();
QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(_finished(QNetworkReply*)));
QString urlString("https://api.vk.com/method/" + method + "?");
std::map<QString, QString>::iterator i;
for (i = data.begin(); i != data.end(); i++) {
urlString += i->first + "=" + i->second + "&";
}
urlString += "&access_token=" + this->token;
QUrl url(urlString);
manager->get(QNetworkRequest(url));
}
void VK::_finished(QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qDebug() << (QString) reply->readAll();
} else {
QString json(reply->readAll());
VKResponse *response = new VKResponse(json);
VKError *error = new VKError(json);
VKAnswer *answer = new VKAnswer(error, response);
emit requestFinished(answer);
}
}
VKResponse::VKResponse(QString json) {
QJsonDocument jsonResponse = QJsonDocument::fromJson(json.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonObject response = jsonObject["response"].toObject();
this->data = &response;
}
VKError::VKError(QString json) {
QJsonDocument jsonResponse = QJsonDocument::fromJson(json.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
if (jsonObject["error"].isNull()) {
this->_error = 0;
this->_text = json;
} else {
this->_text = jsonObject["error"].toString();
this->_error = jsonObject["error"].toObject()["error_code"].toInt();
}
}
QString VKError::text() {
return this->_text;
}
VKAnswer::VKAnswer(VKError *error, VKResponse *response) {
this->error = error;
this->response = response;
}