Created
September 18, 2014 18:15
-
-
Save ttldtor/71f6302c42a8923d0c5a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void TERPConnector::asyncRequest(const QString &url, const QString &requestData, const QString &successfulDataType, std::function<void(QJsonObject)> onSuccess, | |
std::function<void(QJsonObject)> onError, std::function<void(QJsonObject)> onTimeout, int requestTimeout) { | |
QSharedPointer<QNetworkAccessManager> nam = QSharedPointer<QNetworkAccessManager>(new QNetworkAccessManager); | |
QUrl requestUrl(url_.toString() + url); | |
if (nam | |
/*&& nam_->networkAccessible() == QNetworkAccessManager::Accessible*/) { | |
#ifdef DEBUG | |
qDebug() << "asyncRequest: url = " << requestUrl.toString() << ", data = " << requestData << ", succDataType = " << successfulDataType | |
<< ", requestTimeout = " << requestTimeout; | |
#endif | |
QNetworkRequest request(requestUrl); | |
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); | |
request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(requestData.toUtf8().size())); | |
QTimer *t = new QTimer; | |
t->setSingleShot(true); | |
t->setInterval(requestTimeout); | |
QNetworkReply *rep = nam->post(request, requestData.toUtf8()); | |
rep->ignoreSslErrors(); | |
connect(t, &QTimer::timeout, [t, rep, nam, this, onTimeout] { | |
t->disconnect(); | |
t->deleteLater(); | |
if (rep) { | |
rep->abort(); | |
rep->disconnect(); | |
rep->deleteLater(); | |
} | |
onTimeout(QJsonObject()); | |
}); | |
connect(rep, &QNetworkReply::finished, [t, rep, nam, this, onSuccess, onError, successfulDataType] { | |
t->stop(); | |
t->disconnect(); | |
t->deleteLater(); | |
auto r = rep->readAll(); | |
auto o = QJsonDocument::fromJson(r).object(); | |
if (o - successfulDataType) { | |
onSuccess(o); | |
} else { | |
#ifdef DEBUG | |
qDebug() << "asyncRequest: none type or unknown type: " << Utils::toJsonString(o); | |
#endif | |
onError(o); | |
} | |
rep->disconnect(); | |
rep->deleteLater(); | |
}); | |
t->start(); | |
} | |
} | |
void TERPConnector::getCompanies(const QString &sessionName, std::function<void(Companies)> onSuccess, std::function<void(QJsonObject)> onError, | |
std::function<void(QJsonObject)> onTimeout, int requestTimeout) { | |
QJsonObject o; | |
o.insert("type", QLatin1String("GetCompanies")); | |
o.insert("sessionName", sessionName); | |
asyncRequest("/api/admin/company/get/items", Utils::toJsonString(o), "Companies", | |
[onSuccess, this](QJsonObject c) { onSuccess(Companies::createFromJsonObject(c)); }, onError, onTimeout, requestTimeout); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment