Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know which QNetworkReply belong to the QNetworkRequest in async design?

Tags:

qt

qt5

I can easily get async design in C#

HttpResponseMessage response = await httpClient.GetAsync(InputAddress.Text);
{
    ....// run when request finished. And response closely relation to request.
}

But how can I do that in QT? I find some codes below. But still some questions.

  1. Why does (sentReply == reply) can determine whether it is identical or not? Maybe I can send the same request twice,request A,requst B. Corresponding response is A',B'. but the responses arrive followed order B',A'. The code work or not?
  2. If I want run some code when request finished(like c# code above), How can I do that? I think I can bind a UUID to each request or bind a call back function pointer to request? what is the best way to do that?

    QNetworkAccessManager *manager=new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(requestFinished(QNetworkReply*)));
    QNetworkRequest request(QUrl(serverUrl));
    QNetworkReply *sentReply = manager->post(request, buffer.toUtf8());
    
    void requestFinished(QNetworkReply *reply)
    {
        QByteArray msg = reply->readAll();
        if (sentReply == reply)
        qDebug("this is it");
    }
    
like image 328
T_T Avatar asked May 27 '14 05:05

T_T


2 Answers

I would suggest the following:

Add a custom Property to the QNetworkReply by using dynamic properties. In the finished Slot you can access them and call the corresponding method.

Example:

QNetworkReply *reply =  
networkAccessManager->get(QNetworkRequest(QUrl("http://url.com"));
reply->setProperty("login", QVariant("logindata");

connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));

replyFinished slot:

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

if (reply) {
    if (reply->error() == QNetworkReply::NoError) {
        QString myCustomData = reply->property("login").toString();

        if(myCustomData =="logindata")
            //do something

    }

    reply->deleteLater();
}
like image 77
Matthias Avatar answered Oct 15 '22 02:10

Matthias


You can get QNetworkRequest pointer from QNetworkReply

connect(&manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(finishedS(QNetworkReply*)));
//save pointer to orginal request-A in some global(class) variable

void this::finishedS(QNetworkReply* QNR) {
QNetworkRequest *req = QNR->request();
if (req == requestA ) { //request-A stored in global(class) variable
qDebug()<<"It's reply for request-A"
} else {
qDebug()<<"It's reply for request-B"
}
}
like image 28
MKAROL Avatar answered Oct 15 '22 02:10

MKAROL