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.
- 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?
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"); }
You can get QNetworkRequest pointer from QNetworkReply
A graceful way of doing this is connecting to a lambda:
Just pay attention to the scoping rules for captured (between
[]
) variables.In my case I created an array of QNetworkAccessManager and QNetworkReply, I had parallel upload progress bars and I needed to send the progress of each to the respective progress bar.
So, I'm sending the signal of reply[i] to the slot(bar()) and in the slot I used a QNetworkReply object that points to the sender
I removed unnecessary lines, this isn't a working code, I think it gets the point.
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:
replyFinished slot: