← C++

C++ · 20 / 24

Asynchronous HTTP requests with cancellation and deadlines

Load orders without blocking the UI and handle errors, cancellation, size limits and outdated responses.

  • Large
  • Advanced
  • 120 min

Prerequisites: Your first Qt interface with signals and slots, Ownership, lifetime and move semantics, Error handling and the strong exception guarantee

In this tutorial
  1. Start a local service
  2. Receive results through signals
  3. Own and bound requests
  4. Validate transport and payload
  5. Control responses reproducibly
  6. Observe failure cases
  7. Avoid duplicate refresh actions
  8. Exercise and solution
  9. Project context and sources

Download learning package

Setup and verification

GCC with C++20, CMake 3.25 or later, CTest and Python 3. Qt 6.8 with Core, Widgets and Test. Qt Network is also required. Set CMAKE_PREFIX_PATH to your Qt installation if it is not discovered automatically. Locally checked with Qt 6.8.3. Extract the ZIP into a new folder. python3 run_checks.py checks example and solution in a temporary copy and preserves your files. Run python3 verify.py for your own build. The demo is then available at build/order_lab. Qt demos use English labels. Automated widget tests default to offscreen. Run the visible demo in a desktop session without QT_QPA_PLATFORM=offscreen. Native Windows execution is not verified.

Verified on 2026-10-21 on Linux x86_64. Local HTTP connections covering success, HTTP and JSON failures, size limits, deadlines, cancellation and an actually started superseded request. The solution checks duplicate-refresh protection. No external TLS or production-service acceptance test.

A network request may fail, be slow or finish after a newer request has started. OrderDownload therefore owns one active request, an overall deadline and a generation counter. Only the current generation may publish a result. The included local server makes the relevant states reproducible without an external service.

Package contents and individual files

01Start a local service

Run python3 demo_server.py in a terminal. The server binds only to 127.0.0.1 and serves synthetic data at /orders. /error returns HTTP 500, /invalid malformed JSON and /slow a delayed response. This is a teaching fixture without authentication, not a deployed production service.

demo_server.py · pythonOpen file
"""Local synthetic order endpoint. Run with python3 demo_server.py."""

import argparse
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from time import sleep

DOCUMENT = {
    "format": "appfabrik-order-lab",
    "version": 2,
    "orders": [
        {"id": 10, "title": "Deliver motors", "priority": 2, "status": "open"},
        {"id": 20, "title": "Move pallets", "priority": 0, "status": "done"},
    ],
}


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/slow":
            sleep(5)
        status = 500 if self.path == "/error" else 200
        body = (
            b"invalid JSON"
            if self.path == "/invalid"
            else json.dumps(DOCUMENT).encode()
        )
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        try:
            self.wfile.write(body)
        except (BrokenPipeError, ConnectionResetError):
            pass


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=8765)
    args = parser.parse_args()
    print(f"Synthetic orders at http://127.0.0.1:{args.port}/orders", flush=True)
    ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever()
Expected result

The terminal prints the local address on port 8765.

02Receive results through signals

Build with python3 verify.py and run ./build/order_lab. The program connects ready and failed before starting the request. QTimer::singleShot starts it inside the event loop so even immediate rejection exits reliably. An alternative URL can be passed as the first argument.

main.cpp · cppOpen file
#include "download.hpp"
#include <QCoreApplication>
#include <iostream>
int main(int argc, char **argv) {
  QCoreApplication app(argc, argv);
  orders::OrderDownload loader;
  QObject::connect(&loader, &orders::OrderDownload::ready, &app,
                   [&app](const QByteArray &bytes) {
                     std::cout << bytes.toStdString() << '\n';
                     app.exit(0);
                   });
  QObject::connect(&loader, &orders::OrderDownload::failed, &app,
                   [&app](const QString &error) {
                     std::cerr << error.toStdString() << '\n';
                     app.exit(1);
                   });
  QTimer::singleShot(0, &app, [&] {
    loader.load(QUrl(argc > 1 ? argv[1] : "http://127.0.0.1:8765/orders"));
  });
  return app.exec();
}
Expected result

At /orders the JSON is printed. At /error the program exits with failure.

03Own and bound requests

QNetworkAccessManager lives in the same Qt thread as the loader. Each reply is released with deleteLater. A dedicated QTimer limits the entire request to three seconds by default. Reception is capped at 256 KiB. Cancellation and timeout clean up the same active request and each produce only one failure signal.

download.hpp · cppOpen file
#pragma once
#include "json_orders.hpp"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QPointer>
#include <QTimer>

namespace orders {
class OrderDownload final : public QObject {
  Q_OBJECT
  QNetworkAccessManager manager_{this};
  QPointer<QNetworkReply> active_;
  QTimer deadline_{this};
  QByteArray bytes_;
  quint64 generation_{0};
  void discard() {
    ++generation_;
    deadline_.stop();
    if (active_) {
      auto reply = active_;
      active_.clear();
      disconnect(reply, nullptr, this, nullptr);
      reply->abort();
      reply->deleteLater();
    }
    bytes_.clear();
  }
  void fail(const QString &message) {
    discard();
    emit busyChanged(false);
    emit failed(message);
  }
  bool collect(QNetworkReply *reply) {
    bytes_ += reply->read(maximumDocumentBytes + 1 - bytes_.size());
    if (bytes_.size() > maximumDocumentBytes) {
      fail("Response exceeds 256 KiB");
      return false;
    }
    return true;
  }

public:
  explicit OrderDownload(QObject *parent = nullptr) : QObject(parent) {
    deadline_.setSingleShot(true);
    connect(&deadline_, &QTimer::timeout, this,
            [this] { fail("Request timed out"); });
  }
  ~OrderDownload() override { discard(); }
  bool busy() const { return !active_.isNull(); }
  void cancel() {
    if (busy())
      fail("Request cancelled");
  }
  void load(const QUrl &url, int timeoutMs = 3000) {
    discard();
    if (!url.isValid() || url.host().isEmpty() || !url.userInfo().isEmpty() ||
        (url.scheme() != "http" && url.scheme() != "https") || timeoutMs < 1) {
      fail(
          "Expected an HTTP(S) URL without credentials and a positive timeout");
      return;
    }
    QNetworkRequest request(url);
    request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
                         QNetworkRequest::NoLessSafeRedirectPolicy);
    active_ = manager_.get(request);
    active_->setReadBufferSize(maximumDocumentBytes + 1);
    auto *reply = active_.data();
    const auto generation = generation_;
    connect(reply, &QIODevice::readyRead, this, [this, reply, generation] {
      if (generation == generation_)
        collect(reply);
    });
    connect(reply, &QNetworkReply::finished, this, [this, reply, generation] {
      if (generation != generation_) {
        reply->deleteLater();
        return;
      }
      if (!collect(reply))
        return;
      const auto status =
          reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
      if (reply->error() != QNetworkReply::NoError || status < 200 ||
          status >= 300) {
        fail(QString("HTTP %1: %2").arg(status).arg(reply->errorString()));
        return;
      }
      auto decoded = decode(bytes_);
      if (!succeeded(decoded)) {
        fail(QString::fromStdString(std::get<Error>(decoded).message));
        return;
      }
      auto completed = bytes_;
      discard();
      emit busyChanged(false);
      emit ready(completed);
    });
    deadline_.start(timeoutMs);
    emit busyChanged(true);
  }
signals:
  void ready(const QByteArray &document);
  void failed(const QString &message);
  void busyChanged(bool busy);
};
} // namespace orders
Expected result

A slow response is aborted. The loader remains reusable afterward.

04Validate transport and payload

A 2xx HTTP status is not sufficient. The response must contain a valid Order Lab document. The decoder validates version, types, bounds and unique IDs. Tutorial 22 explains the format in more detail. SSL errors are not ignored. Redirects must not downgrade HTTPS to HTTP.

json_orders.hpp · cppOpen file
#pragma once
#include "order.hpp"
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSaveFile>
#include <cmath>

namespace orders {
inline constexpr int maximumDocumentBytes = 262144;
inline bool integer(const QJsonValue &value, int minimum, int maximum) {
  if (!value.isDouble())
    return false;
  double number = value.toDouble();
  return std::isfinite(number) && std::floor(number) == number &&
         number >= minimum && number <= maximum;
}
inline Result<std::vector<Order>> decode(const QByteArray &bytes) {
  if (bytes.size() > maximumDocumentBytes)
    return Error{ErrorCode::invalid, "Document exceeds 256 KiB"};
  QJsonParseError parse;
  auto document = QJsonDocument::fromJson(bytes, &parse);
  if (parse.error != QJsonParseError::NoError || !document.isObject())
    return Error{ErrorCode::invalid, "Expected a JSON object"};
  auto root = document.object();
  if (root.value("format") != "appfabrik-order-lab" ||
      !integer(root.value("version"), 1, 2))
    return Error{ErrorCode::unsupported,
                 "Expected order-lab format version 1 or 2"};
  if (!root.value("orders").isArray() ||
      root.value("orders").toArray().size() > 1000)
    return Error{ErrorCode::invalid,
                 "Expected an array of at most 1000 orders"};
  std::vector<Order> result;
  for (const auto &value : root.value("orders").toArray()) {
    if (!value.isObject())
      return Error{ErrorCode::invalid, "Order must be an object"};
    auto object = value.toObject();
    if (!integer(object.value("id"), 1, 1000000) ||
        !object.value("title").isString())
      return Error{ErrorCode::invalid, "Invalid ID or title"};
    Order order{object.value("id").toInt(),
                object.value("title").toString().toStdString()};
    if (root.value("version").toInt() == 2) {
      if (!integer(object.value("priority"), 0, 2) ||
          (object.value("status") != "open" &&
           object.value("status") != "done"))
        return Error{ErrorCode::invalid, "Invalid priority or status"};
      order.priority = object.value("priority").toInt();
      order.status =
          object.value("status") == "done" ? Status::done : Status::open;
    }
    result.push_back(std::move(order));
  }
  auto valid = validateBatch(result);
  if (!succeeded(valid))
    return std::get<Error>(valid);
  return result;
}
inline Result<QByteArray> encode(std::span<const Order> batch) {
  auto valid = validateBatch(batch);
  if (!succeeded(valid))
    return std::get<Error>(valid);
  QJsonArray items;
  for (const auto &order : batch)
    items.append(QJsonObject{
        {"id", order.id},
        {"title", QString::fromStdString(order.title)},
        {"priority", order.priority},
        {"status", order.status == Status::open ? "open" : "done"}});
  auto bytes = QJsonDocument(QJsonObject{{"format", "appfabrik-order-lab"},
                                         {"version", 2},
                                         {"orders", items}})
                   .toJson(QJsonDocument::Compact);
  if (bytes.size() > maximumDocumentBytes)
    return Error{ErrorCode::invalid, "Encoded document exceeds 256 KiB"};
  return bytes;
}
inline Result<std::vector<Order>> loadFile(const QString &path) {
  QFile file(path);
  if (!file.open(QIODevice::ReadOnly))
    return Error{ErrorCode::storage, file.errorString().toStdString()};
  auto bytes = file.read(maximumDocumentBytes + 1);
  if (file.error() != QFileDevice::NoError)
    return Error{ErrorCode::storage, file.errorString().toStdString()};
  return decode(bytes);
}
inline Result<Done> saveFile(const QString &path,
                             std::span<const Order> batch) {
  auto encoded = encode(batch);
  if (!succeeded(encoded))
    return std::get<Error>(encoded);
  const auto &bytes = std::get<QByteArray>(encoded);
  QSaveFile file(path);
  file.setDirectWriteFallback(false);
  if (!file.open(QIODevice::WriteOnly) || file.write(bytes) != bytes.size() ||
      !file.commit())
    return Error{ErrorCode::storage, file.errorString().toStdString()};
  return Done{};
}
} // namespace orders
Expected result

Malformed JSON emits failed and never reaches ready.

05Control responses reproducibly

The fixture uses an available local port. Status, response body and delay are controllable. The outdated-response test first waits for the server to accept a real initial request. Only then does it start a newer request, testing an in-flight exchange rather than just adjacent function calls.

http_fixture.hpp · cppOpen file
#pragma once
#include "json_orders.hpp"
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#include <QUrl>

class HttpFixture : public QTcpServer {
public:
  QByteArray body =
      R"({"format":"appfabrik-order-lab","version":1,"orders":[{"id":7,"title":"Remote order"}]})";
  int status{200};
  int requests{0};
  int delayMs{0};
  explicit HttpFixture(QObject *parent = nullptr) : QTcpServer(parent) {
    connect(this, &QTcpServer::newConnection, this, [this] {
      while (hasPendingConnections()) {
        auto *socket = nextPendingConnection();
        connect(socket, &QTcpSocket::disconnected, socket,
                &QObject::deleteLater);
        connect(socket, &QTcpSocket::readyRead, socket,
                [this, socket, request = QByteArray{},
                 responded = false]() mutable {
                  request += socket->readAll();
                  if (responded || !request.contains("\r\n\r\n"))
                    return;
                  responded = true;
                  ++requests;
                  const auto reply = "HTTP/1.1 " + QByteArray::number(status) +
                                     " Fixture\r\nContent-Type: "
                                     "application/json\r\nContent-Length: " +
                                     QByteArray::number(body.size()) +
                                     "\r\nConnection: close\r\n\r\n" + body;
                  QTimer::singleShot(delayMs, socket, [socket, reply] {
                    if (socket->state() != QAbstractSocket::ConnectedState)
                      return;
                    socket->write(reply);
                    socket->disconnectFromHost();
                  });
                });
      }
    });
    if (!listen(QHostAddress::LocalHost, 0))
      qFatal("Local HTTP fixture cannot listen");
  }
  QUrl url() const {
    return QUrl(QString("http://127.0.0.1:%1/orders").arg(serverPort()));
  }
};
Expected result

The newer response is the only published result.

06Observe failure cases

QSignalSpy observes success and failure separately. Tests cover HTTP 500, malformed JSON, oversized bodies, unknown versions, timeouts, repeated cancellation and superseded requests. QTRY macros wait with a deadline while processing Qt events. Cancelling a second time must not emit another error.

tests.cpp · cppOpen file
#include "download.hpp"
#include "http_fixture.hpp"
#include <QSignalSpy>
#include <QtTest>
using namespace orders;
class NetworkTests : public QObject {
  Q_OBJECT
private slots:
  void successfulRequest() {
    HttpFixture server;
    OrderDownload loader;
    QSignalSpy ready(&loader, &OrderDownload::ready),
        failed(&loader, &OrderDownload::failed);
    loader.load(server.url());
    QTRY_COMPARE_WITH_TIMEOUT(ready.count(), 1, 2000);
    QCOMPARE(failed.count(), 0);
    QVERIFY(!loader.busy());
    QVERIFY(succeeded(decode(ready.at(0).at(0).toByteArray())));
  }
  void errors_data() {
    QTest::addColumn<int>("status");
    QTest::addColumn<QByteArray>("body");
    QTest::newRow("http") << 500 << QByteArray("{}");
    QTest::newRow("json") << 200 << QByteArray("broken");
    QTest::newRow("oversized")
        << 200 << QByteArray(maximumDocumentBytes + 1, 'x');
    QTest::newRow("schema")
        << 200
        << QByteArray(
               R"({"format":"appfabrik-order-lab","version":99,"orders":[]})");
  }
  void errors() {
    QFETCH(int, status);
    QFETCH(QByteArray, body);
    HttpFixture server;
    server.status = status;
    server.body = body;
    OrderDownload loader;
    QSignalSpy ready(&loader, &OrderDownload::ready),
        failed(&loader, &OrderDownload::failed);
    loader.load(server.url());
    QTRY_COMPARE_WITH_TIMEOUT(failed.count(), 1, 2000);
    QCOMPARE(ready.count(), 0);
    QVERIFY(!loader.busy());
  }
  void timeoutAndCancel() {
    HttpFixture server;
    server.delayMs = 400;
    OrderDownload loader;
    QSignalSpy failed(&loader, &OrderDownload::failed),
        ready(&loader, &OrderDownload::ready);
    loader.load(server.url(), 50);
    QTRY_COMPARE_WITH_TIMEOUT(failed.count(), 1, 1000);
    QVERIFY(failed.at(0).at(0).toString().contains("timed out"));
    loader.load(server.url());
    loader.cancel();
    QCOMPARE(failed.count(), 2);
    loader.cancel();
    QCOMPARE(failed.count(), 2);
    QCOMPARE(ready.count(), 0);
  }
  void supersededReplyCannotWin() {
    HttpFixture slow, fast;
    slow.delayMs = 300;
    fast.body.replace("Remote order", "Latest order");
    OrderDownload loader;
    QSignalSpy ready(&loader, &OrderDownload::ready),
        failed(&loader, &OrderDownload::failed);
    loader.load(slow.url());
    QTRY_COMPARE_WITH_TIMEOUT(slow.requests, 1, 2000);
    loader.load(fast.url());
    QTRY_COMPARE_WITH_TIMEOUT(ready.count(), 1, 2000);
    QVERIFY(ready.at(0).at(0).toByteArray().contains("Latest order"));
    QTest::qWait(400);
    QCOMPARE(ready.count(), 1);
    QCOMPARE(failed.count(), 0);
    loader.load(QUrl("file:///tmp/orders.json"));
    QCOMPARE(failed.count(), 1);
  }
};
QTEST_GUILESS_MAIN(NetworkTests)
#include "tests.moc"
Expected result

All signal and error checks pass against local HTTP connections.

07Avoid duplicate refresh actions

The base class deliberately replaces an active request. A refresh button may instead ignore additional clicks during a request. refreshIfIdle implements that alternative calling rule. The test demonstrates a rejected double click and a permitted refresh after completion.

solution.cpp · cppOpen file
#include "download.hpp"
#include "http_fixture.hpp"
#include <QSignalSpy>
#include <QtTest>
bool refreshIfIdle(orders::OrderDownload &loader, const QUrl &url) {
  if (loader.busy())
    return false;
  loader.load(url);
  return true;
}
class RefreshTest : public QObject {
  Q_OBJECT
private slots:
  void ignoresDoubleClick() {
    HttpFixture server;
    server.delayMs = 50;
    orders::OrderDownload loader;
    QSignalSpy ready(&loader, &orders::OrderDownload::ready);
    QVERIFY(refreshIfIdle(loader, server.url()));
    QVERIFY(!refreshIfIdle(loader, server.url()));
    QTRY_COMPARE_WITH_TIMEOUT(ready.count(), 1, 2000);
    QVERIFY(refreshIfIdle(loader, server.url()));
    QTRY_COMPARE_WITH_TIMEOUT(ready.count(), 2, 2000);
  }
};
QTEST_GUILESS_MAIN(RefreshTest)
#include "solution.moc"
Expected result

Two quick calls start only one request. After completion another call is allowed.

Your exercise

Implement refreshIfIdle. During an active request return false without cancelling that request. Allow another call after completion.

Show the solution and explanation

The solution checks busy before load and reports whether it started. The test uses a delayed local server and waits for two separate successful results. Automatic retries are not introduced here.

solution.cpp · cppOpen file
#include "download.hpp"
#include "http_fixture.hpp"
#include <QSignalSpy>
#include <QtTest>
bool refreshIfIdle(orders::OrderDownload &loader, const QUrl &url) {
  if (loader.busy())
    return false;
  loader.load(url);
  return true;
}
class RefreshTest : public QObject {
  Q_OBJECT
private slots:
  void ignoresDoubleClick() {
    HttpFixture server;
    server.delayMs = 50;
    orders::OrderDownload loader;
    QSignalSpy ready(&loader, &orders::OrderDownload::ready);
    QVERIFY(refreshIfIdle(loader, server.url()));
    QVERIFY(!refreshIfIdle(loader, server.url()));
    QTRY_COMPARE_WITH_TIMEOUT(ready.count(), 1, 2000);
    QVERIFY(refreshIfIdle(loader, server.url()));
    QTRY_COMPARE_WITH_TIMEOUT(ready.count(), 2, 2000);
  }
};
QTEST_GUILESS_MAIN(RefreshTest)
#include "solution.moc"

Project context and sources

Independent teaching project using FactoryForge's logistics theme. The existing FactoryForge source revision provides architectural context. SQLite, networking and import features introduced here belong to the teaching project. Order Lab JSON is a separate format.