QNetworkAccessManager的多个请求

时间:2019-02-18 16:46:35

标签: c++ qt networking qnetworkaccessmanager qnetworkreply

我正尝试发送两个请求,一个请求获取一个身份验证令牌,另一个请求B使用该令牌获取用户信息。

这是我的代码的简化版本:

MyClass::MyClass()
: _manager(new QNetworkAccessManager(this)),
_token(QString()) {
}


void MyClass::authentificationRequest(const QString &username,       
                                     const QString &password) {

    QString credentials =  QString("email=%0&password=%1").arg(username, password);
    QNetworkRequest request(QUrl("https://a.com/log"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QNetworkReply *reply = _manager->post(request, credentials.toUtf8());
    connect(reply, &QNetworkReply::finished, this, &MyClass::reply);
}

void MyClass::userInfoRequest() {

    QNetworkRequest request(QUrl("https://a.com/info"));
    request.setRawHeader("Authorization", QByteArray("Bearer " + _token.toUtf8()));
    QNetworkReply *reply = _manager->get(request);
    connect(reply, &QNetworkReply::finished, this, &MyClass::reply);
}

void MyClass::reply() {

    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());

    if (reply->url() == QUrl { "https://a.com/log" }) {
        storeToken(reply);
        userInfoRequest();
    }

    if (reply->url() == QUrl { "https://a.com/info" }) {
            if (reply->error() == QNetworkReply::NoError) {
            qDebug() << "reading: " << reply->readAll();
        } else {
            qDebug() << reply->error();
        }
    }

    reply->deleteLater();
}

第一个请求得到答复,但是第二个请求却没有答复。如果有人提出解释,我将不胜感激。 预先感谢。

0 个答案:

没有答案