QNetworkAccessManager Class

The QNetworkAccessManager class allows the application to send network requests and receive replies. More...

Header: #include <QNetworkAccessManager>
qmake: QT += network
Since: Qt 4.4
Inherits: QObject

This class was introduced in Qt 4.4.

Note: All functions in this class are reentrant.

Public Types

enum NetworkAccessibility { UnknownAccessibility, NotAccessible, Accessible }
enum Operation { HeadOperation, GetOperation, PutOperation, PostOperation, DeleteOperation, CustomOperation }

Properties

Public Functions

QNetworkAccessManager(QObject *parent = nullptr)
virtual ~QNetworkAccessManager()
QNetworkConfiguration activeConfiguration() const
void addStrictTransportSecurityHosts(const QVector<QHstsPolicy> &knownHosts)
bool autoDeleteReplies() const
QAbstractNetworkCache * cache() const
void clearAccessCache()
void clearConnectionCache()
QNetworkConfiguration configuration() const
void connectToHost(const QString &hostName, quint16 port = 80)
void connectToHostEncrypted(const QString &hostName, quint16 port = 443, const QSslConfiguration &sslConfiguration = QSslConfiguration::defaultConfiguration())
void connectToHostEncrypted(const QString &hostName, quint16 port, const QSslConfiguration &sslConfiguration, const QString &peerName)
QNetworkCookieJar * cookieJar() const
QNetworkReply * deleteResource(const QNetworkRequest &request)
void enableStrictTransportSecurityStore(bool enabled, const QString &storeDir = QString())
QNetworkReply * get(const QNetworkRequest &request)
QNetworkReply * head(const QNetworkRequest &request)
bool isStrictTransportSecurityEnabled() const
bool isStrictTransportSecurityStoreEnabled() const
QNetworkAccessManager::NetworkAccessibility networkAccessible() const
QNetworkReply * post(const QNetworkRequest &request, QIODevice *data)
QNetworkReply * post(const QNetworkRequest &request, const QByteArray &data)
QNetworkReply * post(const QNetworkRequest &request, QHttpMultiPart *multiPart)
QNetworkProxy proxy() const
QNetworkProxyFactory * proxyFactory() const
QNetworkReply * put(const QNetworkRequest &request, QIODevice *data)
QNetworkReply * put(const QNetworkRequest &request, const QByteArray &data)
QNetworkReply * put(const QNetworkRequest &request, QHttpMultiPart *multiPart)
QNetworkRequest::RedirectPolicy redirectPolicy() const
QNetworkReply * sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QIODevice *data = nullptr)
QNetworkReply * sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, const QByteArray &data)
QNetworkReply * sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QHttpMultiPart *multiPart)
void setAutoDeleteReplies(bool shouldAutoDelete)
void setCache(QAbstractNetworkCache *cache)
void setConfiguration(const QNetworkConfiguration &config)
void setCookieJar(QNetworkCookieJar *cookieJar)
void setNetworkAccessible(QNetworkAccessManager::NetworkAccessibility accessible)
void setProxy(const QNetworkProxy &proxy)
void setProxyFactory(QNetworkProxyFactory *factory)
void setRedirectPolicy(QNetworkRequest::RedirectPolicy policy)
void setStrictTransportSecurityEnabled(bool enabled)
QVector<QHstsPolicy> strictTransportSecurityHosts() const
QStringList supportedSchemes() const

Signals

void authenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator)
void encrypted(QNetworkReply *reply)
void finished(QNetworkReply *reply)
void networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible)
void preSharedKeyAuthenticationRequired(QNetworkReply *reply, QSslPreSharedKeyAuthenticator *authenticator)
void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
void sslErrors(QNetworkReply *reply, const QList<QSslError> &errors)

Protected Functions

virtual QNetworkReply * createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &originalReq, QIODevice *outgoingData = nullptr)

Protected Slots

QStringList supportedSchemesImplementation() const

Detailed Description

The Network Access API is constructed around one QNetworkAccessManager object, which holds the common configuration and settings for the requests it sends. It contains the proxy and cache configuration, as well as the signals related to such issues, and reply signals that can be used to monitor the progress of a network operation. One QNetworkAccessManager instance should be enough for the whole Qt application. Since QNetworkAccessManager is based on QObject, it can only be used from the thread it belongs to.

Once a QNetworkAccessManager object has been created, the application can use it to send requests over the network. A group of standard functions are supplied that take a request and optional data, and each return a QNetworkReply object. The returned object is used to obtain any data returned in response to the corresponding request.

A simple download off the network could be accomplished with:

QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished,
        this, &MyClass::replyFinished);

manager->get(QNetworkRequest(QUrl("http://qt-project.org")));

QNetworkAccessManager has an asynchronous API. When the replyFinished slot above is called, the parameter it takes is the QNetworkReply object containing the downloaded data as well as meta-data (headers, etc.).

Note: After the request has finished, it is the responsibility of the user to delete the QNetworkReply object at an appropriate time. Do not directly delete it inside the slot connected to finished(). You can use the deleteLater() function.

Note: QNetworkAccessManager queues the requests it receives. The number of requests executed in parallel is dependent on the protocol. Currently, for the HTTP protocol on desktop platforms, 6 requests are executed in parallel for one host/port combination.

A more involved example, assuming the manager is already existent, can be:

QNetworkRequest request;
request.setUrl(QUrl("http://qt-project.org"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");

QNetworkReply *reply = manager->get(request);
connect(reply, &QIODevice::readyRead, this, &MyClass::slotReadyRead);
connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),
        this, &MyClass::slotError);
connect(reply, &QNetworkReply::sslErrors,
        this, &MyClass::slotSslErrors);

Network and Roaming Support

With the addition of the Bearer Management API to Qt 4.7 QNetworkAccessManager gained the ability to manage network connections. QNetworkAccessManager can start the network interface if the device is offline and terminates the interface if the current process is the last one to use the uplink. Note that some platforms utilize grace periods from when the last application stops using a uplink until the system actually terminates the connectivity link. Roaming is equally transparent. Any queued/pending network requests are automatically transferred to the new access point.

Clients wanting to utilize this feature should not require any changes. In fact it is likely that existing platform specific connection code can simply be removed from the application.

Note: The network and roaming support in QNetworkAccessManager is conditional upon the platform supporting connection management. The QNetworkConfigurationManager::NetworkSessionRequired can be used to detect whether QNetworkAccessManager utilizes this feature.

See also QNetworkRequest, QNetworkReply, and QNetworkProxy.

Member Type Documentation

enum QNetworkAccessManager::NetworkAccessibility

Indicates whether the network is accessible via this network access manager.

Constant Value Description
QNetworkAccessManager::UnknownAccessibility -1 The network accessibility cannot be determined.
QNetworkAccessManager::NotAccessible 0 The network is not currently accessible, either because there is currently no network coverage or network access has been explicitly disabled by a call to setNetworkAccessible().
QNetworkAccessManager::Accessible 1 The network is accessible.

See also networkAccessible.

enum QNetworkAccessManager::Operation

Indicates the operation this reply is processing.

Constant Value Description
QNetworkAccessManager::HeadOperation 1 retrieve headers operation (created with head())
QNetworkAccessManager::GetOperation 2 retrieve headers and download contents (created with get())
QNetworkAccessManager::PutOperation 3 upload contents operation (created with put())
QNetworkAccessManager::PostOperation 4 send the contents of an HTML form for processing via HTTP POST (created with post())
QNetworkAccessManager::DeleteOperation 5 delete contents operation (created with deleteResource())
QNetworkAccessManager::CustomOperation 6 custom operation (created with sendCustomRequest())

This enum was introduced or modified in Qt 4.7.

See also QNetworkReply::operation().

Property Documentation

networkAccessible : NetworkAccessibility

This property holds whether the network is currently accessible via this network access manager.

If the network is not accessible the network access manager will not process any new network requests, all such requests will fail with an error. Requests with URLs with the file:// scheme will still be processed.

By default the value of this property reflects the physical state of the device. Applications may override it to disable all network requests via this network access manager by calling

networkAccessManager->setNetworkAccessible(QNetworkAccessManager::NotAccessible);

Network requests can be re-enabled again, and this property will resume to reflect the actual device state by calling

networkAccessManager->setNetworkAccessible(QNetworkAccessManager::Accessible);

Note: Calling setNetworkAccessible() does not change the network state.

This property was introduced in Qt 4.7.

Access functions:

QNetworkAccessManager::NetworkAccessibility networkAccessible() const
void setNetworkAccessible(QNetworkAccessManager::NetworkAccessibility accessible)

Notifier signal:

void networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible)

Member Function Documentation

QNetworkAccessManager::QNetworkAccessManager(QObject *parent = nullptr)

Constructs a QNetworkAccessManager object that is the center of the Network Access API and sets parent as the parent object.

[signal] void QNetworkAccessManager::authenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator)

This signal is emitted whenever a final server requests authentication before it delivers the requested contents. The slot connected to this signal should fill the credentials for the contents (which can be determined by inspecting the reply object) in the authenticator object.

QNetworkAccessManager will cache the credentials internally and will send the same values if the server requires authentication again, without emitting the authenticationRequired() signal. If it rejects the credentials, this signal will be emitted again.

Note: To have the request not send credentials you must not call setUser() or setPassword() on the authenticator object. This will result in the finished() signal being emitted with a QNetworkReply with error AuthenticationRequiredError.

Note: It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns.

See also proxyAuthenticationRequired(), QAuthenticator::setUser(), and QAuthenticator::setPassword().

[signal] void QNetworkAccessManager::encrypted(QNetworkReply *reply)

This signal is emitted when an SSL/TLS session has successfully completed the initial handshake. At this point, no user data has been transmitted. The signal can be used to perform additional checks on the certificate chain, for example to notify users when the certificate for a website has changed. The reply parameter specifies which network reply is responsible. If the reply does not match the expected criteria then it should be aborted by calling QNetworkReply::abort() by a slot connected to this signal. The SSL configuration in use can be inspected using the QNetworkReply::sslConfiguration() method.

Internally, QNetworkAccessManager may open multiple connections to a server, in order to allow it process requests in parallel. These connections may be reused, which means that the encrypted() signal would not be emitted. This means that you are only guaranteed to receive this signal for the first connection to a site in the lifespan of the QNetworkAccessManager.

This function was introduced in Qt 5.1.

See also QSslSocket::encrypted() and QNetworkReply::encrypted().

[signal] void QNetworkAccessManager::finished(QNetworkReply *reply)

This signal is emitted whenever a pending network reply is finished. The reply parameter will contain a pointer to the reply that has just finished. This signal is emitted in tandem with the QNetworkReply::finished() signal.

See QNetworkReply::finished() for information on the status that the object will be in.

Note: Do not delete the reply object in the slot connected to this signal. Use deleteLater().

See also QNetworkReply::finished() and QNetworkReply::error().

[signal] void QNetworkAccessManager::networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible)

This signal is emitted when the value of the networkAccessible property changes. accessible is the new network accessibility.

Note: Notifier signal for property networkAccessible.

[signal] void QNetworkAccessManager::preSharedKeyAuthenticationRequired(QNetworkReply *reply, QSslPreSharedKeyAuthenticator *authenticator)

This signal is emitted if the SSL/TLS handshake negotiates a PSK ciphersuite, and therefore a PSK authentication is then required. The reply object is the QNetworkReply that is negotiating such ciphersuites.

When using PSK, the client must send to the server a valid identity and a valid pre shared key, in order for the SSL handshake to continue. Applications can provide this information in a slot connected to this signal, by filling in the passed authenticator object according to their needs.

Note: Ignoring this signal, or failing to provide the required credentials, will cause the handshake to fail, and therefore the connection to be aborted.

Note: The authenticator object is owned by the reply and must not be deleted by the application.

This function was introduced in Qt 5.5.

See also QSslPreSharedKeyAuthenticator.

[signal] void QNetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)

This signal is emitted whenever a proxy requests authentication and QNetworkAccessManager cannot find a valid, cached credential. The slot connected to this signal should fill in the credentials for the proxy proxy in the authenticator object.

QNetworkAccessManager will cache the credentials internally. The next time the proxy requests authentication, QNetworkAccessManager will automatically send the same credential without emitting the proxyAuthenticationRequired signal again.

If the proxy rejects the credentials, QNetworkAccessManager will emit the signal again.

See also proxy(), setProxy(), and authenticationRequired().

[signal] void QNetworkAccessManager::sslErrors(QNetworkReply *reply, const QList<QSslError> &errors)

This signal is emitted if the SSL/TLS session encountered errors during the set up, including certificate verification errors. The errors parameter contains the list of errors and reply is the QNetworkReply that is encountering these errors.

To indicate that the errors are not fatal and that the connection should proceed, the QNetworkReply::ignoreSslErrors() function should be called from the slot connected to this signal. If it is not called, the SSL session will be torn down before any data is exchanged (including the URL).

This signal can be used to display an error message to the user indicating that security may be compromised and display the SSL settings (see sslConfiguration() to obtain it). If the user decides to proceed after analyzing the remote certificate, the slot should call ignoreSslErrors().

See also QSslSocket::sslErrors(), QNetworkReply::sslErrors(), QNetworkReply::sslConfiguration(), and QNetworkReply::ignoreSslErrors().

[protected slot] QStringList QNetworkAccessManager::supportedSchemesImplementation() const

Lists all the URL schemes supported by the access manager.

You should not call this function directly; use QNetworkAccessManager::supportedSchemes() instead.

Reimplement this slot to provide your own supported schemes in a QNetworkAccessManager subclass. It is for instance necessary when your subclass provides support for new protocols.

Because of binary compatibility constraints, the supportedSchemes() method (introduced in Qt 5.2) is not virtual. Instead, supportedSchemes() will dynamically detect and call this slot.

This function was introduced in Qt 5.2.

See also supportedSchemes().

[virtual] QNetworkAccessManager::~QNetworkAccessManager()

Destroys the QNetworkAccessManager object and frees up any resources. Note that QNetworkReply objects that are returned from this class have this object set as their parents, which means that they will be deleted along with it if you don't call QObject::setParent() on them.

QNetworkConfiguration QNetworkAccessManager::activeConfiguration() const

Returns the current active network configuration.

If the network configuration returned by configuration() is of type QNetworkConfiguration::ServiceNetwork this function will return the current active child network configuration of that configuration. Otherwise returns the same network configuration as configuration().

Use this function to return the actual network configuration currently in use by the network session.

This function was introduced in Qt 4.7.

See also configuration().

void QNetworkAccessManager::addStrictTransportSecurityHosts(const QVector<QHstsPolicy> &knownHosts)

Adds HTTP Strict Transport Security policies into HSTS cache. knownHosts contains the known hosts that have QHstsPolicy information.

Note: An expired policy will remove a known host from the cache, if previously present.

Note: While processing HTTP responses, QNetworkAccessManager can also update the HSTS cache, removing or updating exitsting policies or introducing new knownHosts. The current implementation thus is server-driven, client code can provide QNetworkAccessManager with previously known or discovered policies, but this information can be overridden by "Strict-Transport-Security" response headers.

This function was introduced in Qt 5.9.

See also addStrictTransportSecurityHosts(), enableStrictTransportSecurityStore(), and QHstsPolicy.

bool QNetworkAccessManager::autoDeleteReplies() const

Returns the true if QNetworkAccessManager is currently configured to automatically delete QNetworkReplies, false otherwise.

This function was introduced in Qt 5.14.

See also setAutoDeleteReplies and QNetworkRequest::AutoDeleteReplyOnFinishAttribute.

QAbstractNetworkCache *QNetworkAccessManager::cache() const

Returns the cache that is used to store data obtained from the network.

This function was introduced in Qt 4.5.

See also setCache().

void QNetworkAccessManager::clearAccessCache()

Flushes the internal cache of authentication data and network connections.

This function is useful for doing auto tests.

This function was introduced in Qt 5.0.

See also clearConnectionCache().

void QNetworkAccessManager::clearConnectionCache()

Flushes the internal cache of network connections. In contrast to clearAccessCache() the authentication data is preserved.

This function was introduced in Qt 5.9.

See also clearAccessCache().

QNetworkConfiguration QNetworkAccessManager::configuration() const

Returns the network configuration that will be used to create the network session which will be used when processing network requests.

This function was introduced in Qt 4.7.

See also setConfiguration() and activeConfiguration().

void QNetworkAccessManager::connectToHost(const QString &hostName, quint16 port = 80)

Initiates a connection to the host given by hostName at port port. This function is useful to complete the TCP handshake to a host before the HTTP request is made, resulting in a lower network latency.

Note: This function has no possibility to report errors.

This function was introduced in Qt 5.2.

See also connectToHostEncrypted(), get(), post(), put(), and deleteResource().

void QNetworkAccessManager::connectToHostEncrypted(const QString &hostName, quint16 port = 443, const QSslConfiguration &sslConfiguration = QSslConfiguration::defaultConfiguration())

Initiates a connection to the host given by hostName at port port, using sslConfiguration. This function is useful to complete the TCP and SSL handshake to a host before the HTTPS request is made, resulting in a lower network latency.

Note: Preconnecting a SPDY connection can be done by calling setAllowedNextProtocols() on sslConfiguration with QSslConfiguration::NextProtocolSpdy3_0 contained in the list of allowed protocols. When using SPDY, one single connection per host is enough, i.e. calling this method multiple times per host will not result in faster network transactions.

Note: This function has no possibility to report errors.

This function was introduced in Qt 5.2.

See also connectToHost(), get(), post(), put(), and deleteResource().

void QNetworkAccessManager::connectToHostEncrypted(const QString &hostName, quint16 port, const QSslConfiguration &sslConfiguration, const QString &peerName)

This is an overloaded function.

Initiates a connection to the host given by hostName at port port, using sslConfiguration with peerName set to be the hostName used for certificate validation. This function is useful to complete the TCP and SSL handshake to a host before the HTTPS request is made, resulting in a lower network latency.

Note: Preconnecting a SPDY connection can be done by calling setAllowedNextProtocols() on sslConfiguration with QSslConfiguration::NextProtocolSpdy3_0 contained in the list of allowed protocols. When using SPDY, one single connection per host is enough, i.e. calling this method multiple times per host will not result in faster network transactions.

Note: This function has no possibility to report errors.

This function was introduced in Qt 5.13.

See also connectToHost(), get(), post(), put(), and deleteResource().

QNetworkCookieJar *QNetworkAccessManager::cookieJar() const

Returns the QNetworkCookieJar that is used to store cookies obtained from the network as well as cookies that are about to be sent.

See also setCookieJar().

[virtual protected] QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &originalReq, QIODevice *outgoingData = nullptr)

Returns a new QNetworkReply object to handle the operation op and request originalReq. The device outgoingData is always 0 for Get and Head requests, but is the value passed to post() and put() in those operations (the QByteArray variants will pass a QBuffer object).

The default implementation calls QNetworkCookieJar::cookiesForUrl() on the cookie jar set with setCookieJar() to obtain the cookies to be sent to the remote server.

The returned object must be in an open state.

QNetworkReply *QNetworkAccessManager::deleteResource(const QNetworkRequest &request)

Sends a request to delete the resource identified by the URL of request.

Note: This feature is currently available for HTTP only, performing an HTTP DELETE request.

This function was introduced in Qt 4.6.

See also get(), post(), put(), and sendCustomRequest().

void QNetworkAccessManager::enableStrictTransportSecurityStore(bool enabled, const QString &storeDir = QString())

If enabled is true, the internal HSTS cache will use a persistent store to read and write HSTS policies. storeDir defines where this store will be located. The default location is defined by QStandardPaths::CacheLocation. If there is no writable QStandartPaths::CacheLocation and storeDir is an empty string, the store will be located in the program's working directory.

Note: If HSTS cache already contains HSTS policies by the time persistent store is enabled, these policies will be preserved in the store. In case both cache and store contain the same known hosts, policies from cache are considered to be more up-to-date (and thus will overwrite the previous values in the store). If this behavior is undesired, enable HSTS store before enabling Strict Tranport Security. By default, the persistent store of HSTS policies is disabled.

This function was introduced in Qt 5.10.

See also isStrictTransportSecurityStoreEnabled(), setStrictTransportSecurityEnabled(), and QStandardPaths::standardLocations().

QNetworkReply *QNetworkAccessManager::get(const QNetworkRequest &request)

Posts a request to obtain the contents of the target request and returns a new QNetworkReply object opened for reading which emits the readyRead() signal whenever new data arrives.

The contents as well as associated headers will be downloaded.

See also post(), put(), deleteResource(), and sendCustomRequest().

Posts a request to obtain the network headers for request and returns a new QNetworkReply object which will contain such headers.

The function is named after the HTTP request associated (HEAD).

bool QNetworkAccessManager::isStrictTransportSecurityEnabled() const

Returns true if HTTP Strict Transport Security (HSTS) was enabled. By default HSTS is disabled.

This function was introduced in Qt 5.9.

See also setStrictTransportSecurityEnabled().

bool QNetworkAccessManager::isStrictTransportSecurityStoreEnabled() const

Returns true if HSTS cache uses a permanent store to load and store HSTS policies.

This function was introduced in Qt 5.10.

See also enableStrictTransportSecurityStore().

QNetworkAccessManager::NetworkAccessibility QNetworkAccessManager::networkAccessible() const

Returns the current network accessibility.

This function was introduced in Qt 4.7.

Note: Getter function for property networkAccessible.

See also setNetworkAccessible().

QNetworkReply *QNetworkAccessManager::post(const QNetworkRequest &request, QIODevice *data)

Sends an HTTP POST request to the destination specified by request and returns a new QNetworkReply object opened for reading that will contain the reply sent by the server. The contents of the data device will be uploaded to the server.

data must be open for reading and must remain valid until the finished() signal is emitted for this reply.

Note: Sending a POST request on protocols other than HTTP and HTTPS is undefined and will probably fail.

See also get(), put(), deleteResource(), and sendCustomRequest().

QNetworkReply *QNetworkAccessManager::post(const QNetworkRequest &request, const QByteArray &data)

This is an overloaded function.

Sends the contents of the data byte array to the destination specified by request.

QNetworkReply *QNetworkAccessManager::post(const QNetworkRequest &request, QHttpMultiPart *multiPart)

This is an overloaded function.

Sends the contents of the multiPart message to the destination specified by request.

This can be used for sending MIME multipart messages over HTTP.

This function was introduced in Qt 4.8.

See also QHttpMultiPart, QHttpPart, and put().

QNetworkProxy QNetworkAccessManager::proxy() const

Returns the QNetworkProxy that the requests sent using this QNetworkAccessManager object will use. The default value for the proxy is QNetworkProxy::DefaultProxy.

See also setProxy(), setProxyFactory(), and proxyAuthenticationRequired().

QNetworkProxyFactory *QNetworkAccessManager::proxyFactory() const

Returns the proxy factory that this QNetworkAccessManager object is using to determine the proxies to be used for requests.

Note that the pointer returned by this function is managed by QNetworkAccessManager and could be deleted at any time.

This function was introduced in Qt 4.5.

See also setProxyFactory() and proxy().

QNetworkReply *QNetworkAccessManager::put(const QNetworkRequest &request, QIODevice *data)

Uploads the contents of data to the destination request and returns a new QNetworkReply object that will be open for reply.

data must be opened for reading when this function is called and must remain valid until the finished() signal is emitted for this reply.

Whether anything will be available for reading from the returned object is protocol dependent. For HTTP, the server may send a small HTML page indicating the upload was successful (or not). Other protocols will probably have content in their replies.

Note: For HTTP, this request will send a PUT request, which most servers do not allow. Form upload mechanisms, including that of uploading files through HTML forms, use the POST mechanism.

See also get(), post(), deleteResource(), and sendCustomRequest().

QNetworkReply *QNetworkAccessManager::put(const QNetworkRequest &request, const QByteArray &data)

This is an overloaded function.

Sends the contents of the data byte array to the destination specified by request.

QNetworkReply *QNetworkAccessManager::put(const QNetworkRequest &request, QHttpMultiPart *multiPart)

This is an overloaded function.

Sends the contents of the multiPart message to the destination specified by request.

This can be used for sending MIME multipart messages over HTTP.

This function was introduced in Qt 4.8.

See also QHttpMultiPart, QHttpPart, and post().

QNetworkRequest::RedirectPolicy QNetworkAccessManager::redirectPolicy() const

Returns the redirect policy that is used when creating new requests.

This function was introduced in Qt 5.9.

See also setRedirectPolicy() and QNetworkRequest::RedirectPolicy.

QNetworkReply *QNetworkAccessManager::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QIODevice *data = nullptr)

Sends a custom request to the server identified by the URL of request.

It is the user's responsibility to send a verb to the server that is valid according to the HTTP specification.

This method provides means to send verbs other than the common ones provided via get() or post() etc., for instance sending an HTTP OPTIONS command.

If data is not empty, the contents of the data device will be uploaded to the server; in that case, data must be open for reading and must remain valid until the finished() signal is emitted for this reply.

Note: This feature is currently available for HTTP(S) only.

This function was introduced in Qt 4.7.

See also get(), post(), put(), and deleteResource().

QNetworkReply *QNetworkAccessManager::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, const QByteArray &data)

This is an overloaded function.

Sends the contents of the data byte array to the destination specified by request.

This function was introduced in Qt 5.8.

QNetworkReply *QNetworkAccessManager::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QHttpMultiPart *multiPart)

This is an overloaded function.

Sends a custom request to the server identified by the URL of request.

Sends the contents of the multiPart message to the destination specified by request.

This can be used for sending MIME multipart messages for custom verbs.

This function was introduced in Qt 5.8.

See also QHttpMultiPart, QHttpPart, and put().

void QNetworkAccessManager::setAutoDeleteReplies(bool shouldAutoDelete)

Enables or disables automatic deletion of QNetworkReplies.

Setting shouldAutoDelete to true is the same as setting the QNetworkRequest::AutoDeleteReplyOnFinishAttribute attribute to true on all future QNetworkRequests passed to this instance of QNetworkAccessManager unless the attribute was already explicitly set on the QNetworkRequest.

This function was introduced in Qt 5.14.

See also autoDeleteReplies and QNetworkRequest::AutoDeleteReplyOnFinishAttribute.

void QNetworkAccessManager::setCache(QAbstractNetworkCache *cache)

Sets the manager's network cache to be the cache specified. The cache is used for all requests dispatched by the manager.

Use this function to set the network cache object to a class that implements additional features, like saving the cookies to permanent storage.

Note: QNetworkAccessManager takes ownership of the cache object.

QNetworkAccessManager by default does not have a set cache. Qt provides a simple disk cache, QNetworkDiskCache, which can be used.

This function was introduced in Qt 4.5.

See also cache() and QNetworkRequest::CacheLoadControl.

void QNetworkAccessManager::setConfiguration(const QNetworkConfiguration &config)

Sets the network configuration that will be used when creating the network session to config.

The network configuration is used to create and open a network session before any request that requires network access is process. If no network configuration is explicitly set via this function the network configuration returned by QNetworkConfigurationManager::defaultConfiguration() will be used.

To restore the default network configuration set the network configuration to the value returned from QNetworkConfigurationManager::defaultConfiguration().

Setting a network configuration means that the QNetworkAccessManager instance will only be using the specified one. In particular, if the default network configuration changes (upon e.g. Wifi being available), this new configuration needs to be enabled manually if desired.

QNetworkConfigurationManager manager;
networkAccessManager->setConfiguration(manager.defaultConfiguration());

If an invalid network configuration is set, a network session will not be created. In this case network requests will be processed regardless, but may fail. For example:

networkAccessManager->setConfiguration(QNetworkConfiguration());

This function was introduced in Qt 4.7.

See also configuration() and QNetworkSession.

void QNetworkAccessManager::setCookieJar(QNetworkCookieJar *cookieJar)

Sets the manager's cookie jar to be the cookieJar specified. The cookie jar is used by all requests dispatched by the manager.

Use this function to set the cookie jar object to a class that implements additional features, like saving the cookies to permanent storage.

Note: QNetworkAccessManager takes ownership of the cookieJar object.

If cookieJar is in the same thread as this QNetworkAccessManager, it will set the parent of the cookieJar so that the cookie jar is deleted when this object is deleted as well. If you want to share cookie jars between different QNetworkAccessManager objects, you may want to set the cookie jar's parent to 0 after calling this function.

QNetworkAccessManager by default does not implement any cookie policy of its own: it accepts all cookies sent by the server, as long as they are well formed and meet the minimum security requirements (cookie domain matches the request's and cookie path matches the request's). In order to implement your own security policy, override the QNetworkCookieJar::cookiesForUrl() and QNetworkCookieJar::setCookiesFromUrl() virtual functions. Those functions are called by QNetworkAccessManager when it detects a new cookie.

See also cookieJar(), QNetworkCookieJar::cookiesForUrl(), and QNetworkCookieJar::setCookiesFromUrl().

void QNetworkAccessManager::setNetworkAccessible(QNetworkAccessManager::NetworkAccessibility accessible)

Overrides the reported network accessibility. If accessible is NotAccessible the reported network accessiblity will always be NotAccessible. Otherwise the reported network accessibility will reflect the actual device state.

This function was introduced in Qt 4.7.

Note: Setter function for property networkAccessible.

See also networkAccessible().

void QNetworkAccessManager::setProxy(const QNetworkProxy &proxy)

Sets the proxy to be used in future requests to be proxy. This does not affect requests that have already been sent. The proxyAuthenticationRequired() signal will be emitted if the proxy requests authentication.

A proxy set with this function will be used for all requests issued by QNetworkAccessManager. In some cases, it might be necessary to select different proxies depending on the type of request being sent or the destination host. If that's the case, you should consider using setProxyFactory().

See also proxy() and proxyAuthenticationRequired().

void QNetworkAccessManager::setProxyFactory(QNetworkProxyFactory *factory)

Sets the proxy factory for this class to be factory. A proxy factory is used to determine a more specific list of proxies to be used for a given request, instead of trying to use the same proxy value for all requests.

All queries sent by QNetworkAccessManager will have type QNetworkProxyQuery::UrlRequest.

For example, a proxy factory could apply the following rules:

  • if the target address is in the local network (for example, if the hostname contains no dots or if it's an IP address in the organization's range), return QNetworkProxy::NoProxy
  • if the request is FTP, return an FTP proxy
  • if the request is HTTP or HTTPS, then return an HTTP proxy
  • otherwise, return a SOCKSv5 proxy server

The lifetime of the object factory will be managed by QNetworkAccessManager. It will delete the object when necessary.

Note: If a specific proxy is set with setProxy(), the factory will not be used.

This function was introduced in Qt 4.5.

See also proxyFactory(), setProxy(), and QNetworkProxyQuery.

void QNetworkAccessManager::setRedirectPolicy(QNetworkRequest::RedirectPolicy policy)

Sets the manager's redirect policy to be the policy specified. This policy will affect all subsequent requests created by the manager.

Use this function to enable or disable HTTP redirects on the manager's level.

Note: When creating a request QNetworkRequest::RedirectAttributePolicy has the highest priority, next by priority is QNetworkRequest::FollowRedirectsAttribute. Finally, the manager's policy has the lowest priority.

For backwards compatibility the default value is QNetworkRequest::ManualRedirectPolicy. This may change in the future and some type of auto-redirect policy will become the default; clients relying on manual redirect handling are encouraged to set this policy explicitly in their code.

This function was introduced in Qt 5.9.

See also redirectPolicy(), QNetworkRequest::RedirectPolicy, and QNetworkRequest::FollowRedirectsAttribute.

void QNetworkAccessManager::setStrictTransportSecurityEnabled(bool enabled)

If enabled is true, QNetworkAccessManager follows the HTTP Strict Transport Security policy (HSTS, RFC6797). When processing a request, QNetworkAccessManager automatically replaces the "http" scheme with "https" and uses a secure transport for HSTS hosts. If it's set explicitly, port 80 is replaced by port 443.

When HSTS is enabled, for each HTTP response containing HSTS header and received over a secure transport, QNetworkAccessManager will update its HSTS cache, either remembering a host with a valid policy or removing a host with an expired or disabled HSTS policy.

This function was introduced in Qt 5.9.

See also isStrictTransportSecurityEnabled().

QVector<QHstsPolicy> QNetworkAccessManager::strictTransportSecurityHosts() const

Returns the list of HTTP Strict Transport Security policies. This list can differ from what was initially set via addStrictTransportSecurityHosts() if HSTS cache was updated from a "Strict-Transport-Security" response header.

This function was introduced in Qt 5.9.

See also addStrictTransportSecurityHosts() and QHstsPolicy.

QStringList QNetworkAccessManager::supportedSchemes() const

Lists all the URL schemes supported by the access manager.

This function was introduced in Qt 5.2.

See also supportedSchemesImplementation().

© The Qt Company Ltd
Licensed under the GNU Free Documentation License, Version 1.3.
https://doc.qt.io/qt-5.14/qnetworkaccessmanager.html