6.0.0-rc4Source

QHttpServerResponder Class

The QHttpServerResponder class writes the response to one request. More…

Header#include <QHttpServerResponder>
CMaketarget_link_libraries(app PRIVATE Nt::HttpServer)
ModuleNt HTTP Server C++ Classes
Since6.4

List of all members, including inherited members

Public Types

Public Functions

QHttpServerResponder(QHttpServerResponder &&other)
~QHttpServerResponder()
voidwrite(QIODevice *data, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)
voidwrite(QIODevice *data, const QByteArray &mimeType, StatusCode status = StatusCode::Ok)
voidwrite(const QJsonDocument &document, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)
voidwrite(const QJsonDocument &document, StatusCode status = StatusCode::Ok)
voidwrite(const QByteArray &data, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)
voidwrite(const QByteArray &data, const QByteArray &mimeType, StatusCode status = StatusCode::Ok)
voidwrite(const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)
voidwrite(StatusCode status = StatusCode::Ok)
voidwriteBeginChunked(const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)
voidwriteBeginChunked(const QHttpHeaders &headers, const QList<QHttpHeaders::WellKnownHeader> &trailerNames, StatusCode status = StatusCode::Ok)
voidwriteBeginChunked(const QByteArray &mimeType, StatusCode status = StatusCode::Ok)
voidwriteChunk(const QByteArray &data)
voidwriteEndChunked(const QByteArray &data, const QHttpHeaders &trailers)
voidwriteEndChunked(const QByteArray &data)
voidsendResponse(const QHttpServerResponse &response)
boolisResponseCanceled() const

Detailed Description

Each request that a QAbstractHttpServer receives comes with a responder. Call one of the write() functions, or sendResponse(), once to send a complete response. To send a body in pieces as it becomes available, call writeBeginChunked(), then writeChunk() as often as needed, and finally writeEndChunked().

// Counts to five, one line per piece of the body.
server.route("/count", [](QHttpServerResponder &responder) {
    responder.writeBeginChunked("text/plain");
    for (int i = 1; i <= 5; ++i)
        responder.writeChunk(QByteArray::number(i) + "\n");
    responder.writeEndChunked("done\n");
});

// Streams a file next to this one from disk; the responder deletes the QFile when it is sent.
server.route("/files/<arg>", [](const QString &name, QHttpServerResponder &responder) {
    if (name.contains("..")) {
        responder.write(QHttpServerResponder::StatusCode::Forbidden);
        return;
    }
    auto *file = new QFile(QFileInfo(QStringLiteral(__FILE__)).absolutePath() + "/" + name);
    if (!file->open(QIODevice::ReadOnly)) {
        delete file;
        responder.write(QHttpServerResponder::StatusCode::NotFound);
        return;
    }
    responder.write(file, "text/plain");
});

// Answers a second later. The responder is moved out of the handler, which returns at once.
server.route("/later", [&app](QHttpServerResponder &responder) {
    auto later = std::make_shared<QHttpServerResponder>(std::move(responder));
    QTimer::singleShot(1000, &app, [later] { later->write("sorry for the wait\n", "text/plain"); });
});

A responder can be moved, for example into a lambda, to answer later. The connection reads no further request until the response is complete. If the client disconnects in the meantime, isResponseCanceled() returns true and writes do nothing.

A responder that is destroyed before it has written anything sends 500 Internal Server Error; one destroyed in the middle of a chunked response closes the connection, so the client sees that the body is incomplete.

The server decides the framing of the response: it sets Content-Length, or uses chunked transfer coding when the length is not known (or, for an HTTP/1.0 client, closes the connection after the body). The same header fields given by the caller are ignored. The body is left out of the response to a HEAD request.

See also QHttpServerResponse and QHttpServer::route().

Differences from Qt

There is no write() for a QFuture.

Member Type Documentation

enum QHttpServerResponder::StatusCode

The HTTP status codes. Each value is the number of the code.

ConstantDescription
QHttpServerResponder::Continue100
QHttpServerResponder::SwitchingProtocols101
QHttpServerResponder::Processing102
QHttpServerResponder::EarlyHints103
QHttpServerResponder::Ok200
QHttpServerResponder::Created201
QHttpServerResponder::Accepted202
QHttpServerResponder::NonAuthoritativeInformation203
QHttpServerResponder::NoContent204. The response has no body.
QHttpServerResponder::ResetContent205
QHttpServerResponder::PartialContent206
QHttpServerResponder::MultiStatus207
QHttpServerResponder::AlreadyReported208
QHttpServerResponder::IMUsed226
QHttpServerResponder::MultipleChoices300
QHttpServerResponder::MovedPermanently301
QHttpServerResponder::Found302
QHttpServerResponder::SeeOther303
QHttpServerResponder::NotModified304. The response has no body.
QHttpServerResponder::UseProxy305
QHttpServerResponder::TemporaryRedirect307
QHttpServerResponder::PermanentRedirect308
QHttpServerResponder::BadRequest400. Also sent by the server for a request it cannot parse.
QHttpServerResponder::Unauthorized401
QHttpServerResponder::PaymentRequired402
QHttpServerResponder::Forbidden403
QHttpServerResponder::NotFound404. Also sent when no route matches.
QHttpServerResponder::MethodNotAllowed405
QHttpServerResponder::NotAcceptable406
QHttpServerResponder::ProxyAuthenticationRequired407
QHttpServerResponder::RequestTimeout408
QHttpServerResponder::Conflict409
QHttpServerResponder::Gone410
QHttpServerResponder::LengthRequired411
QHttpServerResponder::PreconditionFailed412
QHttpServerResponder::PayloadTooLarge413. Also sent by the server for a body over 64 MiB.
QHttpServerResponder::UriTooLong414. Also sent by the server for a request line over 8 KiB.
QHttpServerResponder::UnsupportedMediaType415
QHttpServerResponder::RequestRangeNotSatisfiable416
QHttpServerResponder::ExpectationFailed417
QHttpServerResponder::ImATeapot418
QHttpServerResponder::MisdirectedRequest421
QHttpServerResponder::UnprocessableEntity422
QHttpServerResponder::Locked423
QHttpServerResponder::FailedDependency424
QHttpServerResponder::TooEarly425
QHttpServerResponder::UpgradeRequired426
QHttpServerResponder::PreconditionRequired428
QHttpServerResponder::TooManyRequests429
QHttpServerResponder::RequestHeaderFieldsTooLarge431. Also sent by the server for header fields over 64 KiB.
QHttpServerResponder::UnavailableForLegalReasons451
QHttpServerResponder::InternalServerError500
QHttpServerResponder::NotImplemented501
QHttpServerResponder::BadGateway502
QHttpServerResponder::ServiceUnavailable503
QHttpServerResponder::GatewayTimeout504
QHttpServerResponder::HttpVersionNotSupported505
QHttpServerResponder::VariantAlsoNegotiates506
QHttpServerResponder::InsufficientStorage507
QHttpServerResponder::LoopDetected508
QHttpServerResponder::NotExtended510
QHttpServerResponder::NetworkAuthenticationRequired511
QHttpServerResponder::NetworkConnectTimeoutError599

Member Function Documentation

QHttpServerResponder::QHttpServerResponder(QHttpServerResponder &&other)

Move-constructs a responder from other, which can no longer write.

QHttpServerResponder::~QHttpServerResponder()

Destroys the responder. If it has not written a response yet, 500 Internal Server Error is sent.

bool QHttpServerResponder::isResponseCanceled() const

Returns true if the response can no longer be delivered because the client has disconnected; otherwise returns false.

void QHttpServerResponder::sendResponse(const QHttpServerResponse &response)

Sends response: its status, its header fields and its body.

void QHttpServerResponder::write(QIODevice *data, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)

Sends the contents of data as the body, with the header fields headers and the status status. The responder takes ownership of data and deletes it when it has been sent. The device is opened for reading if it is not open yet.

A random-access device such as a QFile is sent from its current position to its end, with a Content-Length. A sequential device, such as a QProcess, is sent until it closes or emits readChannelFinished(), using chunked transfer coding. The data is read as the connection can take it, so a large file is not loaded into memory.

void QHttpServerResponder::write(QIODevice *data, const QByteArray &mimeType, StatusCode status = StatusCode::Ok)

This is an overloaded function.

Sends the contents of data with the content type mimeType and the status status. The responder takes ownership of data.

void QHttpServerResponder::write(const QJsonDocument &document, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)

Sends document, written compactly, as an application/json body with the header fields headers and the status status.

void QHttpServerResponder::write(const QJsonDocument &document, StatusCode status = StatusCode::Ok)

This is an overloaded function.

Sends document as an application/json body with the status status.

void QHttpServerResponder::write(const QByteArray &data, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)

Sends data as the body, with the header fields headers and the status status.

void QHttpServerResponder::write(const QByteArray &data, const QByteArray &mimeType, StatusCode status = StatusCode::Ok)

This is an overloaded function.

Sends data with the content type mimeType and the status status.

void QHttpServerResponder::write(const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)

This is an overloaded function.

Sends a response without a body, with the header fields headers and the status status.

void QHttpServerResponder::write(StatusCode status = StatusCode::Ok)

This is an overloaded function.

Sends a response without a body and with the status status.

void QHttpServerResponder::writeBeginChunked(const QHttpHeaders &headers, StatusCode status = StatusCode::Ok)

Starts a response with the header fields headers and the status status whose body follows in pieces. Send the pieces with writeChunk() and end the body with writeEndChunked().

See also writeChunk() and writeEndChunked().

void QHttpServerResponder::writeBeginChunked(const QHttpHeaders &headers, const QList<QHttpHeaders::WellKnownHeader> &trailerNames, StatusCode status = StatusCode::Ok)

This is an overloaded function.

Starts a chunked response with the header fields headers and the status status, announcing in a Trailer header that the fields trailerNames will follow the body. Pass their values to writeEndChunked().

void QHttpServerResponder::writeBeginChunked(const QByteArray &mimeType, StatusCode status = StatusCode::Ok)

This is an overloaded function.

Starts a chunked response with the content type mimeType and the status status.

void QHttpServerResponder::writeChunk(const QByteArray &data)

Sends data as the next piece of a chunked response. Empty data is ignored.

See also writeBeginChunked() and writeEndChunked().

void QHttpServerResponder::writeEndChunked(const QByteArray &data, const QHttpHeaders &trailers)

Sends data as the last piece of a chunked response, followed by the trailer fields trailers, and completes the response.

See also writeBeginChunked().

void QHttpServerResponder::writeEndChunked(const QByteArray &data)

This is an overloaded function.

Sends data as the last piece of a chunked response and completes the response.