我如何知道哪个 QNetworkReply 属于异步设计中的 QNetworkRequest? [英] How do I know which QNetworkReply belong to the QNetworkRequest in async design?
问题描述
我可以在 C# 中轻松获得异步设计
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.
}
但是我怎样才能在 QT 中做到这一点呢?我在下面找到了一些代码.但仍有一些问题.
But how can I do that in QT? I find some codes below. But still some questions.
- 为什么(sentReply == reply) 可以判断是否相同?也许我可以发送两次相同的请求,请求 A,请求 B.对应的响应是 A',B'.但响应到达顺序 B',A'.代码是否有效?
如果我想在请求完成时运行一些代码(如上面的 c# 代码),我该怎么做?我想我可以为每个请求绑定一个 UUID 或者绑定一个回调函数指针来请求?最好的方法是什么?
- 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");
}
推荐答案
我建议如下:
使用动态属性将自定义属性添加到 QNetworkReply.在完成的 Slot 中,您可以访问它们并调用相应的方法.
Add a custom Property to the QNetworkReply by using dynamic properties. In the finished Slot you can access them and call the corresponding method.
示例:
QNetworkReply *reply =
networkAccessManager->get(QNetworkRequest(QUrl("http://url.com"));
reply->setProperty("login", QVariant("logindata");
connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
replyFinished slot:
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();
}
这篇关于我如何知道哪个 QNetworkReply 属于异步设计中的 QNetworkRequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!