QNetworkAccessManager

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

Inheritance diagram of PySide2.QtNetwork.QNetworkAccessManager

Synopsis

Functions

Virtual functions

Signals

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:

manager = QNetworkAccessManager(self)
manager.finished[QNetworkReply].connect(self.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:

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

reply = manager.get(request)
reply.readyRead.connect(self.slotReadyRead)
reply.error[QNetworkReply.NetworkError].connect(self..slotError)
reply.sslErrors.connect(self.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 NetworkSessionRequired can be used to detect whether QNetworkAccessManager utilizes this feature.

class QNetworkAccessManager([parent=None])
param parent

QObject

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

PySide2.QtNetwork.QNetworkAccessManager.Operation

Indicates the operation this reply is processing.

Constant

Description

QNetworkAccessManager.HeadOperation

retrieve headers operation (created with head() )

QNetworkAccessManager.GetOperation

retrieve headers and download contents (created with get() )

QNetworkAccessManager.PutOperation

upload contents operation (created with put() )

QNetworkAccessManager.PostOperation

send the contents of an HTML form for processing via HTTP POST (created with post() )

QNetworkAccessManager.DeleteOperation

delete contents operation (created with deleteResource() )

QNetworkAccessManager.CustomOperation

custom operation (created with sendCustomRequest() )

See also

operation()

PySide2.QtNetwork.QNetworkAccessManager.NetworkAccessibility

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

Constant

Description

QNetworkAccessManager.UnknownAccessibility

The network accessibility cannot be determined.

QNetworkAccessManager.NotAccessible

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

The network is accessible.

New in version 4.7.

PySide2.QtNetwork.QNetworkAccessManager.activeConfiguration()
Return type

QNetworkConfiguration

Returns the current active network configuration.

If the network configuration returned by configuration() is of type 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.

See also

configuration()

PySide2.QtNetwork.QNetworkAccessManager.addStrictTransportSecurityHosts(knownHosts)
Parameters

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.

PySide2.QtNetwork.QNetworkAccessManager.authenticationRequired(reply, authenticator)
Parameters
PySide2.QtNetwork.QNetworkAccessManager.cache()
Return type

QAbstractNetworkCache

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

See also

setCache()

PySide2.QtNetwork.QNetworkAccessManager.clearAccessCache()

Flushes the internal cache of authentication data and network connections.

This function is useful for doing auto tests.

PySide2.QtNetwork.QNetworkAccessManager.clearConnectionCache()

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

PySide2.QtNetwork.QNetworkAccessManager.configuration()
Return type

QNetworkConfiguration

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

PySide2.QtNetwork.QNetworkAccessManager.connectToHost(hostName[, port=80])
Parameters
  • hostName – unicode

  • portquint16

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.

PySide2.QtNetwork.QNetworkAccessManager.connectToHostEncrypted(hostName[, port=443[, sslConfiguration=QSslConfiguration.defaultConfiguration()]])
Parameters

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.

PySide2.QtNetwork.QNetworkAccessManager.connectToHostEncrypted(hostName, port, sslConfiguration, peerName)
Parameters
  • hostName – unicode

  • portquint16

  • sslConfigurationQSslConfiguration

  • peerName – unicode

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.

PySide2.QtNetwork.QNetworkAccessManager.cookieJar()
Return type

QNetworkCookieJar

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()

PySide2.QtNetwork.QNetworkAccessManager.createRequest(op, request[, outgoingData=None])
Parameters
Return type

QNetworkReply

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 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.

PySide2.QtNetwork.QNetworkAccessManager.deleteResource(request)
Parameters

requestQNetworkRequest

Return type

QNetworkReply

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.

PySide2.QtNetwork.QNetworkAccessManager.enableStrictTransportSecurityStore(enabled[, storeDir=""])
Parameters
  • enabledbool

  • storeDir – unicode

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 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.

PySide2.QtNetwork.QNetworkAccessManager.encrypted(reply)
Parameters

replyQNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.finished(reply)
Parameters

replyQNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.get(request)
Parameters

requestQNetworkRequest

Return type

QNetworkReply

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.

PySide2.QtNetwork.QNetworkAccessManager.head(request)
Parameters

requestQNetworkRequest

Return type

QNetworkReply

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).

PySide2.QtNetwork.QNetworkAccessManager.isStrictTransportSecurityEnabled()
Return type

bool

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

PySide2.QtNetwork.QNetworkAccessManager.isStrictTransportSecurityStoreEnabled()
Return type

bool

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

PySide2.QtNetwork.QNetworkAccessManager.networkAccessible()
Return type

NetworkAccessibility

Returns the current network accessibility.

PySide2.QtNetwork.QNetworkAccessManager.networkAccessibleChanged(accessible)
Parameters

accessibleNetworkAccessibility

PySide2.QtNetwork.QNetworkAccessManager.networkSessionConnected()
PySide2.QtNetwork.QNetworkAccessManager.post(request, multiPart)
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.post(request, data)
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.post(request, data)
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.preSharedKeyAuthenticationRequired(reply, authenticator)
Parameters
PySide2.QtNetwork.QNetworkAccessManager.proxy()
Return type

QNetworkProxy

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

PySide2.QtNetwork.QNetworkAccessManager.proxyAuthenticationRequired(proxy, authenticator)
Parameters
PySide2.QtNetwork.QNetworkAccessManager.proxyFactory()
Return type

QNetworkProxyFactory

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.

PySide2.QtNetwork.QNetworkAccessManager.put(request, multiPart)
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.put(request, data)
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.put(request, data)
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.redirectPolicy()
Return type

RedirectPolicy

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

See also

setRedirectPolicy() RedirectPolicy

PySide2.QtNetwork.QNetworkAccessManager.sendCustomRequest(request, verb, multiPart)
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.sendCustomRequest(request, verb, data)
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.sendCustomRequest(request, verb[, data=None])
Parameters
Return type

QNetworkReply

PySide2.QtNetwork.QNetworkAccessManager.setCache(cache)
Parameters

cacheQAbstractNetworkCache

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.

See also

cache() CacheLoadControl

PySide2.QtNetwork.QNetworkAccessManager.setConfiguration(config)
Parameters

configQNetworkConfiguration

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 defaultConfiguration() will be used.

To restore the default network configuration set the network configuration to the value returned from 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.

manager = QNetworkConfigurationManager()
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())
PySide2.QtNetwork.QNetworkAccessManager.setCookieJar(cookieJar)
Parameters

cookieJarQNetworkCookieJar

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 cookiesForUrl() and setCookiesFromUrl() virtual functions. Those functions are called by QNetworkAccessManager when it detects a new cookie.

PySide2.QtNetwork.QNetworkAccessManager.setNetworkAccessible(accessible)
Parameters

accessibleNetworkAccessibility

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.

PySide2.QtNetwork.QNetworkAccessManager.setProxy(proxy)
Parameters

proxyQNetworkProxy

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() .

PySide2.QtNetwork.QNetworkAccessManager.setProxyFactory(factory)
Parameters

factoryQNetworkProxyFactory

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 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 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.

PySide2.QtNetwork.QNetworkAccessManager.setRedirectPolicy(policy)
Parameters

policyRedirectPolicy

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 FollowRedirectsAttribute . Finally, the manager’s policy has the lowest priority.

For backwards compatibility the default value is 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.

See also

redirectPolicy() RedirectPolicy FollowRedirectsAttribute

PySide2.QtNetwork.QNetworkAccessManager.setStrictTransportSecurityEnabled(enabled)
Parameters

enabledbool

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.

PySide2.QtNetwork.QNetworkAccessManager.sslErrors(reply, errors)
Parameters
PySide2.QtNetwork.QNetworkAccessManager.strictTransportSecurityHosts()
Return type

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.

PySide2.QtNetwork.QNetworkAccessManager.supportedSchemes()
Return type

list of strings

Lists all the URL schemes supported by the access manager.

PySide2.QtNetwork.QNetworkAccessManager.supportedSchemesImplementation()
Return type

list of strings

Lists all the URL schemes supported by the access manager.

You should not call this function directly; use 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.