QHttpServerResponder Class
The QHttpServerResponder class writes the response to one request. More…
| Header | #include <QHttpServerResponder> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::HttpServer) |
| Module | Nt HTTP Server C++ Classes |
| Since | 6.4 |
List of all members, including inherited members
Public Types
| enum | StatusCode |
Public Functions
| QHttpServerResponder(QHttpServerResponder &&other) | |
| ~QHttpServerResponder() | |
| void | write(QIODevice *data, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok) |
| void | write(QIODevice *data, const QByteArray &mimeType, StatusCode status = StatusCode::Ok) |
| void | write(const QJsonDocument &document, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok) |
| void | write(const QJsonDocument &document, StatusCode status = StatusCode::Ok) |
| void | write(const QByteArray &data, const QHttpHeaders &headers, StatusCode status = StatusCode::Ok) |
| void | write(const QByteArray &data, const QByteArray &mimeType, StatusCode status = StatusCode::Ok) |
| void | write(const QHttpHeaders &headers, StatusCode status = StatusCode::Ok) |
| void | write(StatusCode status = StatusCode::Ok) |
| void | writeBeginChunked(const QHttpHeaders &headers, StatusCode status = StatusCode::Ok) |
| void | writeBeginChunked(const QHttpHeaders &headers, const QList<QHttpHeaders::WellKnownHeader> &trailerNames, StatusCode status = StatusCode::Ok) |
| void | writeBeginChunked(const QByteArray &mimeType, StatusCode status = StatusCode::Ok) |
| void | writeChunk(const QByteArray &data) |
| void | writeEndChunked(const QByteArray &data, const QHttpHeaders &trailers) |
| void | writeEndChunked(const QByteArray &data) |
| void | sendResponse(const QHttpServerResponse &response) |
| bool | isResponseCanceled() 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.
| Constant | Description |
|---|---|
QHttpServerResponder::Continue | 100 |
QHttpServerResponder::SwitchingProtocols | 101 |
QHttpServerResponder::Processing | 102 |
QHttpServerResponder::EarlyHints | 103 |
QHttpServerResponder::Ok | 200 |
QHttpServerResponder::Created | 201 |
QHttpServerResponder::Accepted | 202 |
QHttpServerResponder::NonAuthoritativeInformation | 203 |
QHttpServerResponder::NoContent | 204. The response has no body. |
QHttpServerResponder::ResetContent | 205 |
QHttpServerResponder::PartialContent | 206 |
QHttpServerResponder::MultiStatus | 207 |
QHttpServerResponder::AlreadyReported | 208 |
QHttpServerResponder::IMUsed | 226 |
QHttpServerResponder::MultipleChoices | 300 |
QHttpServerResponder::MovedPermanently | 301 |
QHttpServerResponder::Found | 302 |
QHttpServerResponder::SeeOther | 303 |
QHttpServerResponder::NotModified | 304. The response has no body. |
QHttpServerResponder::UseProxy | 305 |
QHttpServerResponder::TemporaryRedirect | 307 |
QHttpServerResponder::PermanentRedirect | 308 |
QHttpServerResponder::BadRequest | 400. Also sent by the server for a request it cannot parse. |
QHttpServerResponder::Unauthorized | 401 |
QHttpServerResponder::PaymentRequired | 402 |
QHttpServerResponder::Forbidden | 403 |
QHttpServerResponder::NotFound | 404. Also sent when no route matches. |
QHttpServerResponder::MethodNotAllowed | 405 |
QHttpServerResponder::NotAcceptable | 406 |
QHttpServerResponder::ProxyAuthenticationRequired | 407 |
QHttpServerResponder::RequestTimeout | 408 |
QHttpServerResponder::Conflict | 409 |
QHttpServerResponder::Gone | 410 |
QHttpServerResponder::LengthRequired | 411 |
QHttpServerResponder::PreconditionFailed | 412 |
QHttpServerResponder::PayloadTooLarge | 413. Also sent by the server for a body over 64 MiB. |
QHttpServerResponder::UriTooLong | 414. Also sent by the server for a request line over 8 KiB. |
QHttpServerResponder::UnsupportedMediaType | 415 |
QHttpServerResponder::RequestRangeNotSatisfiable | 416 |
QHttpServerResponder::ExpectationFailed | 417 |
QHttpServerResponder::ImATeapot | 418 |
QHttpServerResponder::MisdirectedRequest | 421 |
QHttpServerResponder::UnprocessableEntity | 422 |
QHttpServerResponder::Locked | 423 |
QHttpServerResponder::FailedDependency | 424 |
QHttpServerResponder::TooEarly | 425 |
QHttpServerResponder::UpgradeRequired | 426 |
QHttpServerResponder::PreconditionRequired | 428 |
QHttpServerResponder::TooManyRequests | 429 |
QHttpServerResponder::RequestHeaderFieldsTooLarge | 431. Also sent by the server for header fields over 64 KiB. |
QHttpServerResponder::UnavailableForLegalReasons | 451 |
QHttpServerResponder::InternalServerError | 500 |
QHttpServerResponder::NotImplemented | 501 |
QHttpServerResponder::BadGateway | 502 |
QHttpServerResponder::ServiceUnavailable | 503 |
QHttpServerResponder::GatewayTimeout | 504 |
QHttpServerResponder::HttpVersionNotSupported | 505 |
QHttpServerResponder::VariantAlsoNegotiates | 506 |
QHttpServerResponder::InsufficientStorage | 507 |
QHttpServerResponder::LoopDetected | 508 |
QHttpServerResponder::NotExtended | 510 |
QHttpServerResponder::NetworkAuthenticationRequired | 511 |
QHttpServerResponder::NetworkConnectTimeoutError | 599 |
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.