有时候使用多个有顺序Http请求时(下一个请求需要上一个请求的内容),这时候阻塞功能非常有用。

接口

  • 阻塞当前线程,并进入事件循环。
HttpRequest &block();

实现

  • 使用QEventLoop实现。
QEventLoop loop;
Q ::connect(m_networkReply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec(); /* 阻塞当前线程,如在主线程不会冻结界面。*/

示例

static HttpService http; 
http.get("https://qtbig.com")
    .onResponse([](QByteArray result) { /* 接收数据 */
        qDebug() << "Result: " << result.left(100); 
     })
    .onResponse([](qint64 recv, qint64 total) { /* 接收进度 */
        qDebug() << "Total: " << total << "; Received: " << recv; 
     })
    . ([](QString errorStr) { /* 错误处理 */
        qDebug() << "Error: " << errorStr; 
     })
    .block() /* 阻塞操作 */
    .exec();

关于更多

收藏 打印