QT- QNetworkAccessManager

Time:2024-3-12

1 Introduction

QNetworkAccessManager is a class in the Qt network module that is used to manage network requests and responses. It can send HTTP requests, process HTTP responses, support file uploads and downloads, as well as support multiple network protocols.

QNetworkAccessManager uses an asynchronous approach to sending requests and processing responses, which means it can communicate over the network without blocking the application UI thread. When a request is sent, QNetworkAccessManager will immediately return a QNetworkReply object, which can be used to monitor the progress of the request, access response data, and handle response errors.

QNetworkAccessManager can work with a variety of different request types, including GET, POST, PUT, DELETE, and so on. It also supports setting request headers, query parameters, form data, etc., as well as the ability to set proxy servers.

The basic process of sending an HTTP request using QNetworkAccessManager is as follows:

  • Creating a QNetworkAccessManager Object
  • Create a QNetworkRequest object, set the request URL and request headers
  • Use QNetworkAccessManager’s get(), post(), put() functions to send requests.
  • Processing QNetworkReply objects to get response data

QNetworkAccessManager can be easily integrated into a Qt application to allow the application to communicate with a remote server.

2 Types of public ownership

QT- QNetworkAccessManager

3 Functions

3.1 addStrictTransportSecurityHosts

void addStrictTransportSecurityHosts(const QVector<QHstsPolicy> &knownHosts)
addStrictTransportSecurityHosts is a function in the QNetworkConfigurationManager class used to add HSTS (HTTP Strict Transport Security) policies to the list of known hosts.

HSTS is a web security policy that improves security by informing the browser via an HTTP response header that it can only access the site using an HTTPS connection. After the server sends the HSTS response header, the browser will remember that host’s HSTS policy for a period of time (usually a few months) and automatically redirect all future HTTP requests to HTTPS.Of course, this only applies to sites that already use HTTPS.

In Qt, a host’s HSTS policy can be represented using the QHstsPolicy class, whose constructor accepts a host name and a timestamp parameter. The network security of an application can be enhanced by calling the addStrictTransportSecurityHosts function to add one or more known HSTS policies for a host to the QNetworkConfigurationManager.

The function parameter knownHosts is a vector of type QVector containing the list of hosts to be added.

3.2 autoDeleteReplies

bool QNetworkAccessManager::autoDeleteReplies() const
QNetworkAccessManager::autoDeleteReplies() is a function that returns whether or not the QNetworkAccessManager is currently configured to automatically delete QNetworkReply objects. If set to auto delete, the QNetworkAccessManager will automatically delete the QNetworkReply object when it is finished, otherwise the QNetworkReply object will need to be manually deleted.

This function was introduced in Qt version 5.14.

By default, QNetworkAccessManager’s ability to auto-delete QNetworkReply is enabled, which means that QNetworkAccessManager will automatically delete a QNetworkReply object when it is finished. If you want to manage the QNetworkReply object’s lifecycle manually, you can disable the auto-delete feature by calling QNetworkAccessManager’s setAutoDeleteReplies(false), and then manually delete the QNetworkReply object

3.3 cache

QAbstractNetworkCache *QNetworkAccessManager::cache() const
QNetworkAccessManager::cache() is a function that gets the network data cache used by QNetworkAccessManager. The return is a pointer to a QAbstractNetworkCache object.

QNetworkAccessManager can use caching to store data fetched from the network, thus avoiding duplicate downloads of data. If an application needs to share data between multiple network requests, it can use a cache. By default, QNetworkAccessManager manages the network data cache using the QNetworkDiskCache class, which stores cached data on disk. You can use the setCache() function to set other types of caches, such as QNetworkMemoryCache, which keeps cached data in memory.

void QNetworkAccessManager::setCache(QAbstractNetworkCache *cache)
QNetworkAccessManager::setCache() is a function that sets the network data cache used by QNetworkAccessManager. The cache can be set by passing a pointer to a QAbstractNetworkCache object.QNetworkAccessManager will use the specified cache when processing all network requests. Note that the QNetworkAccessManager will take ownership of the cache object and is responsible for deleting it at the appropriate time.

By default, QNetworkAccessManager does not set the network data cache. You can use the setCache() function to set other types of caches, such as QNetworkMemoryCache or QNetworkDiskCache.Setting the network data cache can improve the performance of your application because it avoids duplicate downloading of data!

3.4 clearAccessCache

void QNetworkAccessManager::clearAccessCache()
QNetworkAccessManager::clearAccessCache() is a function that flushes the authentication data and network connection cache inside QNetworkAccessManager. This function is typically used in situations such as automated testing where the cache needs to be cleared for multiple independent tests.

QNetworkAccessManager maintains an internal cache to store authentication information and network connection information so that it can be reused in future requests. In some cases, it may be necessary to empty these caches, such as when running multiple independent tests, to ensure that each test’s environment is independent.

The following sample code shows how to clear the access cache using the QNetworkAccessManager::clearAccessCache() function:

QNetworkAccessManager *manager = new QNetworkAccessManager();
// Send a request to manager to populate the cache

// Execute the test
// ...

// Empty the cache
manager->clearAccessCache();

// Execute the next test
// ...

delete manager;

In this example, we first create a QNetworkAccessManager object and send some requests to populate the internal cache. Then, some test code is executed, after which the clearAccessCache() function is called to empty the access cache to ensure that the next test environment is independent. Note that the clearAccessCache() function only clears the caches for authentication data and network connection information, not other caches such as the DNS cache or the network data cache. If you need to clear other caches, use a related function such as QNetworkDiskCache::clear().

3.5 clearConnectionCache

void QNetworkAccessManager::clearConnectionCache()
QNetworkAccessManager::clearConnectionCache() is a function that flushes the network connection cache inside QNetworkAccessManager. Unlike clearAccessCache(), this function retains authentication data.

This function was introduced in Qt version 5.9.

QNetworkAccessManager maintains an internal cache to store network connection information so that it can be reused in future requests. In some cases, it may be necessary to clear these caches, such as when running multiple independent tests, to ensure that each test’s environment is independent. Unlike clearAccessCache(), clearConnectionCache() only empties the network connection cache while retaining the authentication data.

3.6 connectToHost

void QNetworkAccessManager::connectToHost(const QString &hostName, quint16 port = 80)
QNetworkAccessManager::connectToHost() is a function that establishes a TCP connection to a specified host before initiating an HTTP request. This function reduces network latency and increases the response speed of HTTP requests.

This function was introduced in Qt version 5.2.

QNetworkAccessManager by default automatically establishes a TCP connection to the target host at the time of the HTTP request. This means that when you initiate an HTTP request, QNetworkAccessManager automatically completes the TCP handshake, establishes a TCP connection, and sends the HTTP request over that connection. Using the connectToHost() function you can manually establish a TCP connection to the host before initiating the HTTP request, thus reducing network latency.

Note that the connectToHost() function has no possibility of error reporting, so it is recommended to use QNetworkAccessManager’s default auto-connect function unless you have a good reason to need to establish a TCP connection manually.

The following sample code shows how to manually establish a TCP connection to a host using the QNetworkAccessManager::connectToHost() function:

QNetworkAccessManager *manager = new QNetworkAccessManager();

// Establish a TCP connection to the host
manager->connectToHost("www.example.com", 80);

// Initiate an HTTP request
QNetworkReply *reply = manager->get(QNetworkRequest(QUrl("http://www.example.com")));
connect(reply, &QNetworkReply::finished, this, [reply]() {
    // Processing response data
    QByteArray data = reply->readAll();
    qDebug() << "Received data:" << data;
});
delete manager;

In this example, we first create a QNetworkAccessManager object and then manually establish a TCP connection to the host using the connectToHost() function. Then we send a GET request to get the QNetworkReply object and process the response data. Note that since the connectToHost() function has no possibility of error reporting, you must ensure that the TCP connection has been successfully established before initiating the HTTP request. If the TCP connection is not successfully established, the HTTP request may fail or time out.

3.7 connectToHostEncrypted

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)
QNetworkAccessManager::connectToHostEncrypted() is a function that establishes a secure TCP connection to a specified host before initiating an HTTPS request. This function can be used to manually establish a secure TCP connection to a host, thus improving the response speed of HTTPS requests.

There can be two versions of this function, one of which requires the peerName parameter, which is used to validate the server’s credentials.

These two functions were introduced in Qt version 4.6.

QNetworkAccessManager by default automatically establishes a secure TCP connection to the target host when an HTTPS request is made. This means that when you initiate an HTTPS request, QNetworkAccessManager automatically completes the SSL handshake, establishes a secure TCP connection, and sends the HTTPS request over that connection. Using the connectToHostEncrypted() function allows you to manually establish a secure TCP connection to the host before initiating an HTTPS request, which improves the response speed of HTTPS requests.

The following sample code shows how to manually establish a secure TCP connection to a host using the QNetworkAccessManager::connectToHostEncrypted() function:

QNetworkAccessManager *manager = new QNetworkAccessManager();

// Establish a secure TCP connection to the host
QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
sslConfig.setProtocol(QSsl::TlsV1_2);
manager->connectToHostEncrypted("www.example.com", 443, sslConfig);

// Initiate an HTTPS request
QNetworkRequest request(QUrl("https://www.example.com"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "text/plain");
QNetworkReply *reply = manager->post(request, QByteArray("hello"));
connect(reply, &QNetworkReply::finished, this, [reply]() {
    // Processing response data
    QByteArray data = reply->readAll();
    qDebug() << "Received data:" << data;
});

delete manager;

In this example, we first create a QNetworkAccessManager object and then manually establish a secure TCP connection to the host using the connectToHostEncrypted() function. Then a POST request is sent to get the QNetworkReply object and the response data is processed. Note that since the connectToHostEncrypted() function needs to manually establish a secure TCP connection, it must ensure that the secure TCP connection has been successfully established before initiating the HTTPS request. If the secure TCP connection is not successfully established, the HTTPS request may fail or time out. In addition, if you use a function that requires the peerName parameter, you need to provide the correct server certificate name for authentication, otherwise the secure connection will not be established.

3.8 cookieJar

QNetworkCookieJar * cookieJar() const
QNetworkAccessManager::cookieJar() is a function that returns the cookie jar object that is being used by QNetworkAccessManager. cookie jar is used to store and manage all HTTP cookies.

An HTTP cookie is a small piece of text information that a server stores on the client side to track a user’s session and identify the user.QNetworkAccessManager automatically manages HTTP cookies by default, both by receiving cookies from the server and by sending cookies in subsequent requests.You can manage HTTP cookies by setting the QNetworkAccessManager can manage HTTP cookies by setting the QNetworkAccessManager’s cookie jar object to share cookie information across multiple requests.

void QNetworkAccessManager::setCookieJar(QNetworkCookieJar *cookieJar)
QNetworkAccessManager::setCookieJar() is a function that sets the cookie jar object that is being used by QNetworkAccessManager.The cookie jar is used to store and manage all the HTTP cookies processed by QNetworkAccessManager.

An HTTP cookie is a small piece of text information that a server stores on the client side to track a user’s session and identify the user.QNetworkAccessManager automatically manages HTTP cookies by default, both by receiving cookies from the server and by sending cookies in subsequent requests.You can manage HTTP cookies by setting the QNetworkAccessManager can manage HTTP cookies by setting the QNetworkAccessManager’s cookie jar object to share cookie information across multiple requests.

The following sample code shows how to set a cookie jar object using the QNetworkAccessManager::setCookieJar() function:

QNetworkAccessManager *manager = new QNetworkAccessManager();

// Set the cookie jar
QNetworkCookieJar *cookieJar = new MyCookieJar();
manager->setCookieJar(cookieJar);

// Initiate an HTTP request
QNetworkRequest request(QUrl("https://www.example.com"));
QNetworkReply *reply = manager->get(request);
connect(reply, &QNetworkReply::finished, this, [reply]() {
    // Processing response data
    QByteArray data = reply->readAll();
    qDebug() << "Received data:" << data;
});

delete manager;

In this example, we first create a QNetworkAccessManager object and then use the setCookieJar() function to set the cookie jar object to a custom MyCookieJar object. Next, we send a GET request to get the QNetworkReply object and process the response data. Note that in practice, if you need more sophisticated cookie management, you can implement your own QNetworkCookieJar subclass and override the QNetworkCookieJar :setCookiesFromUrl() function to implement your own security policy.

3.9 deleteResource

QNetworkReply *QNetworkAccessManager::deleteResource(const QNetworkRequest &request)
QNetworkAccessManager::deleteResource() is a function that sends an HTTP DELETE request to delete the resource corresponding to the URL identified by request. This function can only be used with the HTTP protocol.
An HTTP DELETE request is used to ask the server to delete a resource corresponding to a specified URL. You can easily send a DELETE request to the server by using the QNetworkAccessManager deleteResource() function.

3.10 enableStrictTransportSecurityStore

void QNetworkAccessManager::enableStrictTransportSecurityStore(bool enabled, const QString &storeDir = QString())
QNetworkAccessManager :CacheLocation, the cache directory. If there is no writable cache directory and storeDir is an empty string, the storage path will be in the program’s working directory.

Note that if persistent storage is enabled, QNetworkAccessManager writes HSTS policies to disk and reads the cached policies from disk. If the cache already contains some HSTS policies before enabling persistent storage, these policies will be kept in the cache and the policies in the cache will overwrite the policies in the disk. Therefore, the cache should be emptied before enabling persistent storage. Also, if both the cache and the persistent storage contain the same hostname and HSTS policies, the policies in the cache will be considered up-to-date and overwrite the policies in the persistent storage.

3.11 get

QNetworkReply *QNetworkAccessManager::get(const QNetworkRequest &request)
QNetworkAccessManager::get() is a function that sends an HTTP GET request and returns a new QNetworkReply object for reading the response data. The QNetworkReply object emits the readyRead() signal when new data is obtained.

HTTP GET request is used to request the server to get the resource corresponding to the specified URL. Using QNetworkAccessManager’s get() function, you can easily send a GET request to the server and read the response data.

QNetworkAccessManager *manager = new QNetworkAccessManager();

// Send a GET request
QUrl url("https://www.example.com");
QNetworkRequest request(url);
QNetworkReply *reply = manager->get(request);
connect(reply, &QNetworkReply::finished, this, [reply]() {
    // Processing response data
    QByteArray data = reply->readAll();
    qDebug() << "Received data:" << data;
});

delete manager;

3.12 head

QNetworkReply *QNetworkAccessManager::head(const QNetworkRequest &request)
QNetworkAccessManager::head() is a function that sends an HTTP HEAD request, gets the network headers associated with the request, and returns a new QNetworkReply object to contain those headers.

An HTTP HEAD request is similar to an HTTP GET request, but returns only the HTTP headers associated with the request, not the actual resource content. Typically, HTTP HEAD requests are used to obtain metadata about a resource or to check if a resource exists without actually downloading the resource content.

QNetworkAccessManager *manager = new QNetworkAccessManager();

// Send a HEAD request
QUrl url("https://www.example.com");
QNetworkRequest request(url);
QNetworkReply *reply = manager->head(request);
connect(reply, &QNetworkReply::finished, this, [reply]() {
    // Process response header data
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    QVariant contentLength = reply->header(QNetworkRequest::ContentLengthHeader);
    qDebug() << "Status code:" << statusCode.toInt();
    qDebug() << "Content length:" << contentLength.toInt();
});

delete manager;

3.13 isStrictTransportSecurityEnabled

bool QNetworkAccessManager::isStrictTransportSecurityEnabled() const
QNetworkAccessManager::isStrictTransportSecurityEnabled() is a function that determines whether HTTP Strict Transport Security (HSTS) is enabled. Returns true if it is enabled; otherwise returns false. by default, HSTS is disabled.

HTTP Strict Transport Security (HSTS) is a security mechanism used to protect web applications from SSL stripping attacks and session hijacking attacks. When a client and server establish an HTTPS connection for the first time, the server can send an HSTS response header to the client requesting that the client always use HTTPS to access the site for the next period of time (e.g., 6 months). During the HSTS lifecycle, if the client tries to connect to the site using HTTP, the browser automatically redirects the request to HTTPS.

3.14 isStrictTransportSecurityStoreEnabled

bool QNetworkAccessManager::isStrictTransportSecurityStoreEnabled() const
QNetworkAccessManager::isStrictTransportSecurityStoreEnabled() is a function that determines whether persistent storage is enabled for the HTTP Strict Transport Security (HSTS) cache. Returns true if it is enabled; otherwise returns false.

3.15 post

QNetworkReply * post(const QNetworkRequest &request, QIODevice *data)
QNetworkReply * post(const QNetworkRequest &request, const QByteArray &data)
QNetworkReply * post(const QNetworkRequest &request, QHttpMultiPart *multiPart)

In the first form of overloading, the data parameter is a QIODevice object, which can be used to send binary data, file data and so on. Here is a sample code:

QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request(QUrl("https://www.example.com/upload"));

QFile *file = new QFile("test.txt");
file->open(QIODevice::ReadOnly);

QNetworkReply *reply = manager->post(request, file);
file->setParent(reply); // set owner to reply so that reply can close the file when it destructs.

// Handle data reads for reply, etc.

delete manager;

In this example, we first create a QNetworkAccessManager object and a QNetworkRequest object, then we create a QFile object and open the file with the open() function. Finally, we use the QNetworkAccessManager’s post() function to send the contents of the file and set the file object as a child of the QNetworkReply object. When reply is destructed, the file object is also automatically closed.

The second form of overloading, data parameter is a QByteArray object, can be used to send plain text data, JSON data and so on. Here is a sample code:

QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request(QUrl("https://www.example.com/api"));

QByteArray postData;
postData.append("username=johndoe&password=secret");

QNetworkReply *reply = manager->post(request, postData);

// Handle data reads for reply, etc.

delete manager;

In this example, we first create a QNetworkAccessManager object and a QNetworkRequest object, then we create a QByteArray object and write the POST data to that object. Finally, we use the QNetworkAccessManager’s post() function to send the POST request and handle the data reading and other operations of the reply object.

The third form of overloading, multiPart parameter is a QHttpMultiPart object, can be used to send files, form data, etc. QHttpMultiPart is a more complex object, can contain multiple QHttpPart object. The following is a sample code:

QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request(QUrl("https://www.example.com/upload"));

QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart textPart;
textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"username\""));
textPart.setBody("johndoe");

QHttpPart filePart;
filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"test.jpg\""));

QFile *file = new QFile("test.jpg");
file->open(QIODevice::ReadOnly);
filePart.setBodyDevice(file);
file->setParent(multiPart); // owner is set to multiPart so that the file can be closed when multiPart destructs.

multiPart->append(textPart);
multiPart->append(filePart);

QNetworkReply *reply = manager->post(request, multiPart);
multiPart->setParent(reply); // set owner to reply so that multiPart can be deleted when reply destructs.

// Handle data reads for reply, etc.

delete manager;

In this example, we first create a QNetworkAccessManager object and a QNetworkRequest object, then we create a QHttpMultiPart object and two QHttpPart objects for sending plain text data and file data. Finally, we send a POST request using the QNetworkAccessManager’s post() function and set the QHttpMultiPart object as a child of the QNetworkReply object. When reply is destructed, the QHttpMultiPart object is also automatically deleted.

3.16 proxy

QNetworkProxy proxy() const
This function returns the proxy server configuration of the QNetworkAccessManager object. If the QNetworkAccessManager object does not have a proxy server set, an empty QNetworkProxy object is returned.

3.17 proxyFactory

QNetworkProxyFactory * proxyFactory() const
This function returns the proxy factory for the QNetworkAccessManager object. The proxy factory is used to create a QNetworkProxy object so that the QNetworkAccessManager object can forward network requests using a proxy server. If the QNetworkAccessManager object does not have a proxy factory set, an empty QNetworkProxyFactory object is returned.

3.18 put

QNetworkReply * put(const QNetworkRequest &request, QIODevice *data)
QNetworkReply * put(const QNetworkRequest &request, const QByteArray &data)
QNetworkReply * put(const QNetworkRequest &request, QHttpMultiPart *multiPart)

In the first form of overloading, the data parameter is a QIODevice object, which can be used to send binary data, file data and so on. Here is a sample code:

QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request(QUrl("https://www.example.com/upload"));

QFile *file = new QFile("test.txt");
file->open(QIODevice::ReadOnly);

QNetworkReply *reply = manager->put(request, file);
file->setParent(reply); // set owner to reply so that reply can close the file when it destructs.

// Handle data reads for reply, etc.

delete manager;

In this example, we first create a QNetworkAccessManager object and a QNetworkRequest object, then we create a QFile object and open the file with the open() function. Finally, we use the QNetworkAccessManager’s put() function to send the contents of the file and set the file object as a child of the QNetworkReply object. When reply is destructed, the file object is also automatically closed.

The second form of overloading, data parameter is a QByteArray object, can be used to send plain text data, JSON data and so on. Here is a sample code:

QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request(QUrl("https://www.example.com/api"));

QByteArray putData;
putData.append("username=johndoe&password=secret");

QNetworkReply *reply = manager->put(request, putData);

// Handle data reads for reply, etc.

delete manager;

In this example, we first create a QNetworkAccessManager object and a QNetworkRequest object, then we create a QByteArray object and write the PUT data to that object. Finally, we use the QNetworkAccessManager’s put() function to send the PUT request and handle operations such as reading data from the reply object.

The third form of overloading, multiPart parameter is a QHttpMultiPart object, can be used to send files, form data, etc. QHttpMultiPart is a more complex object, can contain multiple QHttpPart object. The following is a sample code:

QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request(QUrl("https://www.example.com/upload"));

QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart textPart;
textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"username\""));
textPart.setBody("johndoe");

QHttpPart filePart;
filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"test.jpg\""));

QFile *file = new QFile("test.jpg");
file->open(QIODevice::ReadOnly);
filePart.setBodyDevice(file);
file->setParent(multiPart); // owner is set to multiPart so that the file can be closed when multiPart destructs.

multiPart->append(textPart);
multiPart->append(filePart);

QNetworkReply *reply = manager->put(request, multiPart);
multiPart->setParent(reply); // set owner to reply so that multiPart can be deleted when reply destructs.

// Handle data reads for reply, etc.

delete manager;

3.19 redirectPolicy

QNetworkRequest::RedirectPolicy redirectPolicy() const
The redirectPolicy() function in the QNetworkRequest class can be used to get the redirection policy for a web request. Redirection means that when the URL of a network request changes, the server returns a redirect response to the client so that the client can jump to the new URL. The redirection policy determines the behavior of the web request when it encounters a redirection response.

This function returns the redirection policy of the QNetworkRequest object, which is an enumerated value of type QNetworkRequest :RedirectPolicy:

  • QNetworkRequest::ManualRedirectPolicy: Indicates that when a network request encounters a redirect response, it will not automatically jump to the new URL, but will emit a finished() signal, and it is up to the programmer to decide whether or not to make the jump.
  • QNetworkRequest::AutoRedirectPolicy: indicates that the network request will automatically jump to a new URL when it encounters a redirect response.
  • QNetworkRequest::NoLessSafeRedirectPolicy: Indicates that when a network request encounters a redirect response, it will only jump to a safer URL than the original URL.
  • QNetworkRequest::SameOriginRedirectPolicy: Indicates that when a network request encounters a redirect response, it will only jump to a URL that belongs to the same domain as the original URL.

Below is a sample code:

QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request(QUrl("https://www.example.com/old_url"));

// Set the redirect policy to ManualRedirectPolicy
request.setRedirectPolicy(QNetworkRequest::ManualRedirectPolicy);

QNetworkReply *reply = manager->get(request);

connect(reply, &QNetworkReply::finished, [=]() {
    if (reply->error() == QNetworkReply::NoError) {
        QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
        qDebug() << "The request was redirected to" << redirectUrl;

        // Manually jump to a new URL
        request.setUrl(redirectUrl);
        reply = manager->get(request);
    } else {
        qDebug() << "Failed to perform the request:" << reply->errorString();
    }

    reply->deleteLater();
});

delete manager;

In this example, we first create a QNetworkAccessManager object and a QNetworkRequest object and set the redirection policy to ManualRedirectPolicy.Then, we use the QNetworkAccessManager’s get() function to send the network request and emit the finished() signal when the request is complete. In the signal slot function, we determine whether the request was successful or not, and if it was successful, we get the redirect URL and manually jump to the new URL using QNetworkAccessManager’s get() function. If the request fails, an error message is output.

Note: In the above example, we manually jumped to the new URL, which may lead to some security issues, so the ManualRedirectPolicy policy should be used with caution in real development. In general, we recommend using AutoRedirectPolicy policy.

3.20 sendCustomReques

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)
The sendCustomRequest() function in the QNetworkAccessManager class can be used to send customized network requests that use any HTTP method (e.g. GET, POST, PUT, etc.). These custom requests are different from the get(), post(), put() functions provided in QNetworkAccessManager because they use custom HTTP methods, so we need to set the request headers manually.

3.21 setAutoDeleteReplies

void setAutoDeleteReplies(bool shouldAutoDelete)

3.22 setCache

void setCache(QAbstractNetworkCache *cache)
void setCookieJar(QNetworkCookieJar *cookieJar)
void setProxy(const QNetworkProxy &proxy)
void setProxyFactory(QNetworkProxyFactory *factory)
void setRedirectPolicy(QNetworkRequest::RedirectPolicy policy)
void setStrictTransportSecurityEnabled(bool enabled)
void setTransferTimeout(int timeout = QNetworkRequest::DefaultTransferTimeoutConstant)
QVector<QHstsPolicy> strictTransportSecurityHosts() const
QStringList supportedSchemes() const
int transferTimeout() const

4 Signals

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

5 Protected Functions

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

6 Protected Slots

QStringList supportedSchemesImplementation() const