QNetworkReply 等待完成
我正在使用 Qt 4.6.3 和以下不起作用的代码
QStringList userInfo;
QNetworkRequest netRequest(QUrl("http://api.stackoverflow.com/1.1/users/587532"));
QNetworkReply *netReply = netman->get(netRequest);
// from here onwards not working
netReply->waitForReadyRead(-1);
if (netReply->isFinished()==true)
{userInfo << do sth to reply;}
return userInfo;
,因为该函数返回一个空的 QStringList,应用程序崩溃。如何等到请求完成,然后在一个函数内处理回复
I am using Qt 4.6.3 and the following not-working code
QStringList userInfo;
QNetworkRequest netRequest(QUrl("http://api.stackoverflow.com/1.1/users/587532"));
QNetworkReply *netReply = netman->get(netRequest);
// from here onwards not working
netReply->waitForReadyRead(-1);
if (netReply->isFinished()==true)
{userInfo << do sth to reply;}
return userInfo;
as this function returns an empty QStringList, the app crashes. How to wait until the request has finished and then process the reply within one function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用事件循环:
您还应该考虑添加一些比网络超时更短的时间(20 秒?)。即使发生错误,我也不确定是否会调用 finish 。因此,您也有可能连接到错误信号。
You can use event loop:
Also you should consider adding some shorter then network timeout (20s?). I'm not sure if finished is called even if an error occured. So it is possible, that you have connect to error signal also.
这里的这些回复都使用旧语法,不适用于最新的QT。
等待网络请求完成:
These replies here are all using old syntax and do not apply to the latest QT.
To wait for the network request to finish:
首先,我建议您阅读 Qt 文档参考中的相关文档,您可以在这里找到: http ://doc.qt.nokia.com/latest/classes.html。
查看您的代码示例,您似乎已经拥有了
QNetworkRequest
和QNetworkReply
以及QNetworkAccessManager
。您需要的是将一个槽连接到finished(QNetworkReply *)
信号。每当待处理的网络回复完成时,就会发出此信号。现在,在您的插槽中,您可以读取响应您的请求而发送的数据。像这样的东西:
编辑:
要同步等待信号,请使用 QEventLoop。您在这里有一个示例
http://wiki.forum.nokia.com/index.php/ How_to_wait_synchronously_for_a_Signal_in_Qt
First I recommend you to read the relevant documentation from the Qt Documentation Reference that you can find here: http://doc.qt.nokia.com/latest/classes.html.
Looking at your code sample it seems that you already have, along side with
QNetworkRequest
andQNetworkReply
, aQNetworkAccessManager
. What you need is to connect a slot to thefinished(QNetworkReply *)
signal. This signal is emitted whenever a pending network reply is finished.Now, in your slot, you can read the data which was sent in response to your request. Something like:
EDIT:
To wait synchronously for a signal use QEventLoop. You have an example here
http://wiki.forum.nokia.com/index.php/How_to_wait_synchronously_for_a_Signal_in_Qt