c++qtqt5qnetworkrequest

QNetworkAccessManager connected to 2 reply slots, how do I know which reply belongs to which request


I have 1 QNetworkAccessManager in my application and I am making 2 requests at the same time. When I get the reply back from the manager the replies are not in the order I called them and that makes sense. How can I work around that? Should I have another manager to weed out any request queues issues?

QNetworkRequest request1(ONE_GET);
request1.setRawHeader("Content-Type", "application/vnd.api+json");
request1.setRawHeader("Accept", "application/vnd.api+json");  
m_nam.get(request1);

connect(&m_nam, &QNetworkAccessManager::finished,this , &HelperClass::onReply1Recieved);

QNetworkRequest request2(TWO_GET);
request2.setRawHeader("Content-Type", "application/vnd.api+json");
request2.setRawHeader("Accept", "application/vnd.api+json");

m_nam.get(request2);

connect(&m_nam, &QNetworkAccessManager::finished,this , &HelperClass::onReply2Recieved);

Solution

  • The problem in your case is that both slots are connecting to the same signal so both will be notified and even if you try to disconnect the signal that does not guarantee that it works correctly, the solution is to connect the signal of each of the QNetworkReply:

    QNetworkRequest request1(ONE_GET);
    request1.setRawHeader("Content-Type", "application/vnd.api+json");
    request1.setRawHeader("Accept", "application/vnd.api+json");  
    QNetworkReply *reply1 = m_nam.get(request1);
    connect(reply1, &QNetworkReply::finished, this, &HelperClass::onReply1Recieved);
    
    
    QNetworkRequest request2(TWO_GET);
    request2.setRawHeader("Content-Type", "application/vnd.api+json");
    request2.setRawHeader("Accept", "application/vnd.api+json");
    QNetworkReply *reply2 = m_nam.get(request2);
    connect(reply2, &QNetworkReply::finished, this, &HelperClass::onReply2Recieved);
    

    void HelperClass::onReply1Recieved(){
        QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
        qDebug() << reply->readAll();
    }
    
    void HelperClass::onReply2Recieved(){
        QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
        qDebug() << reply->readAll();
    }