The QNetworkRequest class holds a request to be sent with QNetworkAccessManager. More...
Header: | #include <QNetworkRequest> |
CMake: | find_package(Qt6 REQUIRED COMPONENTS Network) target_link_libraries(mytarget PRIVATE Qt6::Network) |
qmake: | QT += network |
enum | Attribute { HttpStatusCodeAttribute, HttpReasonPhraseAttribute, RedirectionTargetAttribute, ConnectionEncryptedAttribute, CacheLoadControlAttribute, …, UserMax } |
enum | CacheLoadControl { AlwaysNetwork, PreferNetwork, PreferCache, AlwaysCache } |
enum | KnownHeaders { ContentDispositionHeader, ContentTypeHeader, ContentLengthHeader, LocationHeader, LastModifiedHeader, …, ServerHeader } |
enum | LoadControl { Automatic, Manual } |
enum | Priority { HighPriority, NormalPriority, LowPriority } |
enum | RedirectPolicy { ManualRedirectPolicy, NoLessSafeRedirectPolicy, SameOriginRedirectPolicy, UserVerifiedRedirectPolicy } |
enum | TransferTimeoutConstant { DefaultTransferTimeoutConstant } |
QNetworkRequest(const QNetworkRequest &other) | |
QNetworkRequest(const QUrl &url) | |
QNetworkRequest() | |
QNetworkRequest & | operator=(const QNetworkRequest &other) |
~QNetworkRequest() | |
QVariant | attribute(QNetworkRequest::Attribute code, const QVariant &defaultValue = QVariant()) const |
qint64 | decompressedSafetyCheckThreshold() const |
bool | hasRawHeader(const QByteArray &headerName) const |
QVariant | header(QNetworkRequest::KnownHeaders header) const |
QHttp2Configuration | http2Configuration() const |
int | maximumRedirectsAllowed() const |
QObject * | originatingObject() const |
QString | peerVerifyName() const |
QNetworkRequest::Priority | priority() const |
QByteArray | rawHeader(const QByteArray &headerName) const |
QList<QByteArray> | rawHeaderList() const |
void | setAttribute(QNetworkRequest::Attribute code, const QVariant &value) |
void | setDecompressedSafetyCheckThreshold(qint64 threshold) |
void | setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value) |
void | setHttp2Configuration(const QHttp2Configuration &configuration) |
void | setMaximumRedirectsAllowed(int maxRedirectsAllowed) |
void | setOriginatingObject(QObject *object) |
void | setPeerVerifyName(const QString &peerName) |
void | setPriority(QNetworkRequest::Priority priority) |
void | setRawHeader(const QByteArray &headerName, const QByteArray &headerValue) |
void | setSslConfiguration(const QSslConfiguration &config) |
void | setTransferTimeout(int timeout = DefaultTransferTimeoutConstant) |
void | setUrl(const QUrl &url) |
QSslConfiguration | sslConfiguration() const |
void | swap(QNetworkRequest &other) |
int | transferTimeout() const |
QUrl | url() const |
bool | operator!=(const QNetworkRequest &other) const |
bool | operator==(const QNetworkRequest &other) const |
QNetworkRequest is part of the Network Access API and is the class holding the information necessary to send a request over the network. It contains a URL and some ancillary information that can be used to modify the request.
See also QNetworkReply and QNetworkAccessManager.
Attribute codes for the QNetworkRequest and QNetworkReply.
Attributes are extra meta-data that are used to control the behavior of the request and to pass further information from the reply back to the application. Attributes are also extensible, allowing custom implementations to pass custom values.
The following table explains what the default attribute codes are, the QVariant types associated, the default value if said attribute is missing and whether it's used in requests or replies.
Constant | Value | Description |
---|---|---|
QNetworkRequest::HttpStatusCodeAttribute |
0 |
Replies only, type: QMetaType::Int (no default) Indicates the HTTP status code received from the HTTP server (like 200, 304, 404, 401, etc.). If the connection was not HTTP-based, this attribute will not be present. |
QNetworkRequest::HttpReasonPhraseAttribute |
1 |
Replies only, type: QMetaType::QByteArray (no default) Indicates the HTTP reason phrase as received from the HTTP server (like "Ok", "Found", "Not Found", "Access Denied", etc.) This is the human-readable representation of the status code (see above). If the connection was not HTTP-based, this attribute will not be present. |
QNetworkRequest::RedirectionTargetAttribute |
2 |
Replies only, type: QMetaType::QUrl (no default) If present, it indicates that the server is redirecting the request to a different URL. The Network Access API does follow redirections by default, unless QNetworkRequest::ManualRedirectPolicy is used. Additionally, if QNetworkRequest::UserVerifiedRedirectPolicy is used, then this attribute will be set if the redirect was not followed. The returned URL might be relative. Use QUrl::resolved() to create an absolute URL out of it. |
QNetworkRequest::ConnectionEncryptedAttribute |
3 |
Replies only, type: QMetaType::Bool (default: false) Indicates whether the data was obtained through an encrypted (secure) connection. |
QNetworkRequest::CacheLoadControlAttribute |
4 |
Requests only, type: QMetaType::Int (default: QNetworkRequest::PreferNetwork) Controls how the cache should be accessed. The possible values are those of QNetworkRequest::CacheLoadControl. Note that the default QNetworkAccessManager implementation does not support caching. However, this attribute may be used by certain backends to modify their requests (for example, for caching proxies). |
QNetworkRequest::CacheSaveControlAttribute |
5 |
Requests only, type: QMetaType::Bool (default: true) Controls if the data obtained should be saved to cache for future uses. If the value is false, the data obtained will not be automatically cached. If true, data may be cached, provided it is cacheable (what is cacheable depends on the protocol being used). |
QNetworkRequest::SourceIsFromCacheAttribute |
6 |
Replies only, type: QMetaType::Bool (default: false) Indicates whether the data was obtained from cache or not. |
QNetworkRequest::DoNotBufferUploadDataAttribute |
7 |
Requests only, type: QMetaType::Bool (default: false) Indicates whether the QNetworkAccessManager code is allowed to buffer the upload data, e.g. when doing a HTTP POST. When using this flag with sequential upload data, the ContentLengthHeader header must be set. |
QNetworkRequest::HttpPipeliningAllowedAttribute |
8 |
Requests only, type: QMetaType::Bool (default: false) Indicates whether the QNetworkAccessManager code is allowed to use HTTP pipelining with this request. |
QNetworkRequest::HttpPipeliningWasUsedAttribute |
9 |
Replies only, type: QMetaType::Bool Indicates whether the HTTP pipelining was used for receiving this reply. |
QNetworkRequest::CustomVerbAttribute |
10 |
Requests only, type: QMetaType::QByteArray Holds the value for the custom HTTP verb to send (destined for usage of other verbs than GET, POST, PUT and DELETE). This verb is set when calling QNetworkAccessManager::sendCustomRequest(). |
QNetworkRequest::CookieLoadControlAttribute |
11 |
Requests only, type: QMetaType::Int (default: QNetworkRequest::Automatic) Indicates whether to send 'Cookie' headers in the request. This attribute is set to false by Qt WebKit when creating a cross-origin XMLHttpRequest where withCredentials has not been set explicitly to true by the Javascript that created the request. See here for more information. (This value was introduced in 4.7.) |
QNetworkRequest::CookieSaveControlAttribute |
13 |
Requests only, type: QMetaType::Int (default: QNetworkRequest::Automatic) Indicates whether to save 'Cookie' headers received from the server in reply to the request. This attribute is set to false by Qt WebKit when creating a cross-origin XMLHttpRequest where withCredentials has not been set explicitly to true by the Javascript that created the request. See here for more information. (This value was introduced in 4.7.) |
QNetworkRequest::AuthenticationReuseAttribute |
12 |
Requests only, type: QMetaType::Int (default: QNetworkRequest::Automatic) Indicates whether to use cached authorization credentials in the request, if available. If this is set to QNetworkRequest::Manual and the authentication mechanism is 'Basic' or 'Digest', Qt will not send an an 'Authorization' HTTP header with any cached credentials it may have for the request's URL. This attribute is set to QNetworkRequest::Manual by Qt WebKit when creating a cross-origin XMLHttpRequest where withCredentials has not been set explicitly to true by the Javascript that created the request. See here for more information. (This value was introduced in 4.7.) |
QNetworkRequest::BackgroundRequestAttribute |
17 |
Type: QMetaType::Bool (default: false) Indicates that this is a background transfer, rather than a user initiated transfer. Depending on the platform, background transfers may be subject to different policies. |
QNetworkRequest::Http2AllowedAttribute |
19 |
Requests only, type: QMetaType::Bool (default: true) Indicates whether the QNetworkAccessManager code is allowed to use HTTP/2 with this request. This applies to SSL requests or 'cleartext' HTTP/2 if Http2CleartextAllowedAttribute is set. |
QNetworkRequest::Http2WasUsedAttribute |
20 |
Replies only, type: QMetaType::Bool (default: false) Indicates whether HTTP/2 was used for receiving this reply. (This value was introduced in 5.9.) |
QNetworkRequest::EmitAllUploadProgressSignalsAttribute |
18 |
Requests only, type: QMetaType::Bool (default: false) Indicates whether all upload signals should be emitted. By default, the uploadProgress signal is emitted only in 100 millisecond intervals. (This value was introduced in 5.5.) |
QNetworkRequest::OriginalContentLengthAttribute |
21 |
Replies only, type QMetaType::Int Holds the original content-length attribute before being invalidated and removed from the header when the data is compressed and the request was marked to be decompressed automatically. (This value was introduced in 5.9.) |
QNetworkRequest::RedirectPolicyAttribute |
22 |
Requests only, type: QMetaType::Int, should be one of the QNetworkRequest::RedirectPolicy values (default: NoLessSafeRedirectPolicy). (This value was introduced in 5.9.) |
QNetworkRequest::Http2DirectAttribute |
23 |
Requests only, type: QMetaType::Bool (default: false) If set, this attribute will force QNetworkAccessManager to use HTTP/2 protocol without initial HTTP/2 protocol negotiation. Use of this attribute implies prior knowledge that a particular server supports HTTP/2. The attribute works with SSL or with 'cleartext' HTTP/2 if Http2CleartextAllowedAttribute is set. If a server turns out to not support HTTP/2, when HTTP/2 direct was specified, QNetworkAccessManager gives up, without attempting to fall back to HTTP/1.1. If both Http2AllowedAttribute and Http2DirectAttribute are set, Http2DirectAttribute takes priority. (This value was introduced in 5.11.) |
QNetworkRequest::AutoDeleteReplyOnFinishAttribute |
25 |
Requests only, type: QMetaType::Bool (default: false) If set, this attribute will make QNetworkAccessManager delete the QNetworkReply after having emitted "finished". (This value was introduced in 5.14.) |
QNetworkRequest::ConnectionCacheExpiryTimeoutSecondsAttribute |
26 |
Requests only, type: QMetaType::Int To set when the TCP connections to a server (HTTP1 and HTTP2) should be closed after the last pending request had been processed. (This value was introduced in 6.3.) |
QNetworkRequest::Http2CleartextAllowedAttribute |
27 |
Requests only, type: QMetaType::Bool (default: false) If set, this attribute will tell QNetworkAccessManager to attempt an upgrade to HTTP/2 over cleartext (also known as h2c). Until Qt 7 the default value for this attribute can be overridden to true by setting the QT_NETWORK_H2C_ALLOWED environment variable. This attribute is ignored if the Http2AllowedAttribute is not set. (This value was introduced in 6.3.) |
QNetworkRequest::User |
1000 |
Special type. Additional information can be passed in QVariants with types ranging from User to UserMax. The default implementation of Network Access will ignore any request attributes in this range and it will not produce any attributes in this range in replies. The range is reserved for extensions of QNetworkAccessManager. |
QNetworkRequest::UserMax |
32767 |
Special type. See User. |
Controls the caching mechanism of QNetworkAccessManager.
Constant | Value | Description |
---|---|---|
QNetworkRequest::AlwaysNetwork |
0 |
always load from network and do not check if the cache has a valid entry (similar to the "Reload" feature in browsers); in addition, force intermediate caches to re-validate. |
QNetworkRequest::PreferNetwork |
1 |
default value; load from the network if the cached entry is older than the network entry. This will never return stale data from the cache, but revalidate resources that have become stale. |
QNetworkRequest::PreferCache |
2 |
load from cache if available, otherwise load from network. Note that this can return possibly stale (but not expired) items from cache. |
QNetworkRequest::AlwaysCache |
3 |
only load from cache, indicating error if the item was not cached (i.e., off-line mode) |
List of known header types that QNetworkRequest parses. Each known header is also represented in raw form with its full HTTP name.
Constant | Value | Description |
---|---|---|
QNetworkRequest::ContentDispositionHeader |
6 |
Corresponds to the HTTP Content-Disposition header and contains a string containing the disposition type (for instance, attachment) and a parameter (for instance, filename). |
QNetworkRequest::ContentTypeHeader |
0 |
Corresponds to the HTTP Content-Type header and contains a string containing the media (MIME) type and any auxiliary data (for instance, charset). |
QNetworkRequest::ContentLengthHeader |
1 |
Corresponds to the HTTP Content-Length header and contains the length in bytes of the data transmitted. |
QNetworkRequest::LocationHeader |
2 |
Corresponds to the HTTP Location header and contains a URL representing the actual location of the data, including the destination URL in case of redirections. |
QNetworkRequest::LastModifiedHeader |
3 |
Corresponds to the HTTP Last-Modified header and contains a QDateTime representing the last modification date of the contents. |
QNetworkRequest::IfModifiedSinceHeader |
9 |
Corresponds to the HTTP If-Modified-Since header and contains a QDateTime. It is usually added to a QNetworkRequest. The server shall send a 304 (Not Modified) response if the resource has not changed since this time. |
QNetworkRequest::ETagHeader |
10 |
Corresponds to the HTTP ETag header and contains a QString representing the last modification state of the contents. |
QNetworkRequest::IfMatchHeader |
11 |
Corresponds to the HTTP If-Match header and contains a QStringList. It is usually added to a QNetworkRequest. The server shall send a 412 (Precondition Failed) response if the resource does not match. |
QNetworkRequest::IfNoneMatchHeader |
12 |
Corresponds to the HTTP If-None-Match header and contains a QStringList. It is usually added to a QNetworkRequest. The server shall send a 304 (Not Modified) response if the resource does match. |
QNetworkRequest::CookieHeader |
4 |
Corresponds to the HTTP Cookie header and contains a QList<QNetworkCookie> representing the cookies to be sent back to the server. |
QNetworkRequest::SetCookieHeader |
5 |
Corresponds to the HTTP Set-Cookie header and contains a QList<QNetworkCookie> representing the cookies sent by the server to be stored locally. |
QNetworkRequest::UserAgentHeader |
7 |
The User-Agent header sent by HTTP clients. |
QNetworkRequest::ServerHeader |
8 |
The Server header received by HTTP clients. |
See also header(), setHeader(), rawHeader(), and setRawHeader().
Indicates if an aspect of the request's loading mechanism has been manually overridden, e.g. by Qt WebKit.
Constant | Value | Description |
---|---|---|
QNetworkRequest::Automatic |
0 |
default value: indicates default behaviour. |
QNetworkRequest::Manual |
1 |
indicates behaviour has been manually overridden. |
This enum lists the possible network request priorities.
Constant | Value | Description |
---|---|---|
QNetworkRequest::HighPriority |
1 |
High priority |
QNetworkRequest::NormalPriority |
3 |
Normal priority |
QNetworkRequest::LowPriority |
5 |
Low priority |
[since 5.9]
enum QNetworkRequest::RedirectPolicyIndicates whether the Network Access API should automatically follow a HTTP redirect response or not.
Constant | Value | Description |
---|---|---|
QNetworkRequest::ManualRedirectPolicy |
0 |
Not following any redirects. |
QNetworkRequest::NoLessSafeRedirectPolicy |
1 |
Default value: Only "http"->"http", "http" -> "https" or "https" -> "https" redirects are allowed. |
QNetworkRequest::SameOriginRedirectPolicy |
2 |
Require the same protocol, host and port. Note, http://example.com and http://example.com:80 will fail with this policy (implicit/explicit ports are considered to be a mismatch). |
QNetworkRequest::UserVerifiedRedirectPolicy |
3 |
Client decides whether to follow each redirect by handling the redirected() signal, emitting redirectAllowed() on the QNetworkReply object to allow the redirect or aborting/finishing it to reject the redirect. This can be used, for example, to ask the user whether to accept the redirect, or to decide based on some app-specific configuration. |
Note: When Qt handles redirects it will, for legacy and compatibility reasons, issue the redirected request using GET when the server returns a 301 or 302 response, regardless of the original method used, unless it was HEAD.
This enum was introduced or modified in Qt 5.9.
[since 5.15]
enum QNetworkRequest::TransferTimeoutConstantA constant that can be used for enabling transfer timeouts with a preset value.
Constant | Value | Description |
---|---|---|
QNetworkRequest::DefaultTransferTimeoutConstant |
30000 |
The transfer timeout in milliseconds. Used if setTimeout() is called without an argument. |
This enum was introduced or modified in Qt 5.15.
Creates a copy of other.
Constructs a QNetworkRequest object with url as the URL to be requested.
Constructs a QNetworkRequest object with no URL to be requested. Use setUrl() to set one.
Creates a copy of other
Disposes of the QNetworkRequest object.
Returns the attribute associated with the code code. If the attribute has not been set, it returns defaultValue.
Note: This function does not apply the defaults listed in QNetworkRequest::Attribute.
See also setAttribute() and QNetworkRequest::Attribute.
[since 6.2]
qint64 QNetworkRequest::decompressedSafetyCheckThreshold() constReturns the threshold for archive bomb checks.
If the decompressed size of a reply is smaller than this, Qt will simply decompress it, without further checking.
This function was introduced in Qt 6.2.
See also setDecompressedSafetyCheckThreshold().
Returns true
if the raw header headerName is present in this network request.
See also rawHeader() and setRawHeader().
Returns the value of the known network header header if it is present in this request. If it is not present, returns QVariant() (i.e., an invalid variant).
See also KnownHeaders, rawHeader(), and setHeader().
[since 5.14]
QHttp2Configuration QNetworkRequest::http2Configuration()
constReturns the current parameters that QNetworkAccessManager is using for this request and its underlying HTTP/2 connection. This is either a configuration previously set by an application or a default configuration.
The default values that QNetworkAccessManager is using are:
By default, server push is disabled, Huffman compression and string indexing are enabled.
This function was introduced in Qt 5.14.
See also setHttp2Configuration.
[since 5.6]
int QNetworkRequest::maximumRedirectsAllowed() constReturns the maximum number of redirects allowed to be followed for this request.
This function was introduced in Qt 5.6.
See also setMaximumRedirectsAllowed().
Returns a reference to the object that initiated this network request; returns nullptr
if not set or the object has been destroyed.
See also setOriginatingObject().
[since 5.13]
QString QNetworkRequest::peerVerifyName() constReturns the host name set for the certificate validation, as set by setPeerVerifyName. By default this returns a null string.
This function was introduced in Qt 5.13.
See also setPeerVerifyName.
Return the priority of this request.
See also setPriority().
Returns the raw form of header headerName. If no such header is present, an empty QByteArray is returned, which may be indistinguishable from a header that is present but has no content (use hasRawHeader() to find out if the header exists or not).
Raw headers can be set with setRawHeader() or with setHeader().
See also header() and setRawHeader().
Returns a list of all raw headers that are set in this network request. The list is in the order that the headers were set.
See also hasRawHeader() and rawHeader().
Sets the attribute associated with code code to be value value. If the attribute is already set, the previous value is discarded. In special, if value is an invalid QVariant, the attribute is unset.
See also attribute() and QNetworkRequest::Attribute.
[since 6.2]
void QNetworkRequest::setDecompressedSafetyCheckThreshold(qint64 threshold)Sets the threshold for archive bomb checks.
Some supported compression algorithms can, in a tiny compressed file, encode a spectacularly huge decompressed file. This is only possible if the decompressed content is extremely monotonous, which is seldom the case for real files being transmitted in good faith: files exercising such insanely high compression ratios are typically payloads of buffer-overrun attacks, or denial-of-service (by using up too much memory) attacks. Consequently, files that decompress to huge sizes, particularly from tiny compressed forms, are best rejected as suspected malware.
If a reply's decompressed size is bigger than this threshold (by default, 10 MiB, i.e. 10 * 1024 * 1024), Qt will check the compression ratio: if that is unreasonably large (40:1 for GZip and Deflate, or 100:1 for Brotli and
ZStandard), the reply will be treated as an error. Setting the threshold to -1
disables this check.
This function was introduced in Qt 6.2.
See also decompressedSafetyCheckThreshold().
Sets the value of the known header header to be value, overriding any previously set headers. This operation also sets the equivalent raw HTTP header.
See also KnownHeaders, setRawHeader(), and header().
[since 5.14]
void QNetworkRequest::setHttp2Configuration(const QHttp2Configuration &configuration)Sets request's HTTP/2 parameters from configuration.
Note: The configuration must be set prior to making a request.
Note: HTTP/2 multiplexes several streams in a single HTTP/2 connection. This implies that QNetworkAccessManager will use the configuration found in the first request from a series of requests sent to the same host.
This function was introduced in Qt 5.14.
See also http2Configuration, QNetworkAccessManager, and QHttp2Configuration.
[since 5.6]
void QNetworkRequest::setMaximumRedirectsAllowed(int
maxRedirectsAllowed)Sets the maximum number of redirects allowed to be followed for this request to maxRedirectsAllowed.
This function was introduced in Qt 5.6.
See also maximumRedirectsAllowed().
Allows setting a reference to the object initiating the request.
For example Qt WebKit sets the originating object to the QWebFrame that initiated the request.
See also originatingObject().
[since 5.13]
void QNetworkRequest::setPeerVerifyName(const QString
&peerName)Sets peerName as host name for the certificate validation, instead of the one used for the TCP connection.
This function was introduced in Qt 5.13.
See also peerVerifyName.
Set the priority of this request to priority.
Note: The priority is only a hint to the network access manager. It can use it or not. Currently it is used for HTTP to decide which request should be sent first to a server.
See also priority().
Sets the header headerName to be of value headerValue. If headerName corresponds to a known header (see QNetworkRequest::KnownHeaders), the raw format will be parsed and the corresponding "cooked" header will be set as well.
For example:
request.setRawHeader(QByteArray("Last-Modified"), QByteArray("Sun, 06 Nov 1994 08:49:37 GMT"));
will also set the known header LastModifiedHeader to be the QDateTime object of the parsed date.
Note: Setting the same header twice overrides the previous setting. To accomplish the behaviour of multiple HTTP headers of the same name, you should concatenate the two values, separating them with a comma (",") and set one single raw header.
See also KnownHeaders, setHeader(), hasRawHeader(), and rawHeader().
Sets this network request's SSL configuration to be config. The settings that apply are the private key, the local certificate, the TLS protocol (e.g. TLS 1.3), the CA certificates and the ciphers that the SSL backend is allowed to use.
See also sslConfiguration() and QSslConfiguration::defaultConfiguration().
[since 5.15]
void QNetworkRequest::setTransferTimeout(int timeout =
DefaultTransferTimeoutConstant)Sets timeout as the transfer timeout in milliseconds.
Transfers are aborted if no bytes are transferred before the timeout expires. Zero means no timer is set. If no argument is provided, the timeout is QNetworkRequest::DefaultTransferTimeoutConstant. If this function is not called, the timeout is disabled and has the value zero.
This function was introduced in Qt 5.15.
See also transferTimeout.
Sets the URL this network request is referring to be url.
See also url().
Returns this network request's SSL configuration. By default this is the same as QSslConfiguration::defaultConfiguration().
See also setSslConfiguration() and QSslConfiguration::defaultConfiguration().
[since 5.0]
void QNetworkRequest::swap(QNetworkRequest
&other)Swaps this network request with other. This function is very fast and never fails.
This function was introduced in Qt 5.0.
[since 5.15]
int QNetworkRequest::transferTimeout() constReturns the timeout used for transfers, in milliseconds.
This timeout is zero if setTransferTimeout hasn't been called, which means that the timeout is not used.
This function was introduced in Qt 5.15.
See also setTransferTimeout.
Returns the URL this network request is referring to.
See also setUrl().
Returns false
if this object is not the same as other.
See also operator==().
Returns true
if this object is the same as other (i.e., if they have the same URL, same headers and same meta-data settings).
See also operator!=().