Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

How to use http cookies with Qt

From Wiki
Jump to: navigation, search
Article Metadata
Created: gnuton (31 Dec 2010)
Last edited: hamishwillee (11 Oct 2012)


A cookie, also known as a web cookie, browser cookie, and HTTP cookie, is a piece of text stored by a user's web browser. A cookie can be used for authentication, storing site preferences, shopping cart contents, the identifier for a server-based session, or anything else that can be accomplished through storing text data. A cookie consists of one or more name-value pairs containing bits of information, which may be encrypted for information privacy and data security purposes. The cookie is sent as an HTTP header by a web server to a web browser and then sent back unchanged by the browser each time it accesses that server.


The Qt Network module offers the class QNetworkCookieJar which can be used with QNetworkAccessManager to manage cookies in Qt applications. The following class will show you how to send a post request to a URL and read the cookies stored in the header.

#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkCookieJar>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QDebug>
class cookiesHandler: public QObject{
cookiesHandler(QObject *parent = 0) : QObject(parent){
mManager = new QNetworkAccessManager(this);
mManager->setCookieJar(new QNetworkCookieJar(this));
connect(mManager, SIGNAL(finished(QNetworkReply*)), SLOT(replyFinished(QNetworkReply*)));
void sendPostRequest(const QUrl &url, const QByteArray &data){
mUrl = url;
QNetworkRequest r(mUrl);
mManager->post(r, data);
virtual ~cookiesHandler(){}
private slots:
void replyFinished(QNetworkReply *reply){
if (reply->error() != QNetworkReply::NoError){
qWarning() << "ERROR:" << reply->errorString();
QList<QNetworkCookie> cookies = mManager->cookieJar()->cookiesForUrl(mUrl);
qDebug() << "COOKIES for" << << cookies;
QNetworkAccessManager *mManager;
QUrl mUrl;

The previous class can be used as follow:

QUrl url(""); // https and http are both allowed.
QByteArray postData;
c.sendPostRequest(url, postData);

The cookie can be sent back to the server with another request in this way:

QList<QNetworkCookie>  cookies = mManager->cookieJar()->cookiesForUrl(mUrl);
QVariant var;
QNetworkRequest r(QUrl(""));
r.setHeader(QNetworkRequest::CookieHeader, var);
This page was last modified on 11 October 2012, at 01:17.
231 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.