How do I save cookies with Qt?
Asked Answered
A

3

5

I am trying to save cookies that are produced by my app to disk location such as C:\Users\Username\AppData\Local\MyCompany\MyApp. I have implemented a webview and have pretty much finished coding my simple browser the final thing to do is save cookies.

I am can qDebug() the cookies I get from the webapp and they show the cookies are formed correctly but I am a)unsure where to go from there and b) not 100% sure on how to make a subclass of the cookiejar class?

Below I create my cookiejar object in my MainWindow constructor

view = new QWebView(this);
jar = new QNetworkCookieJar;
view->page()->networkAccessManager()->setCookieJar(jar);

And in my replyfinished slot I can see the cookie contained in the reply and I attempt to save it but nothing happens and I receive no run time errors. There isn't a great deal of stuff out there on this and have seen a few posts where the instruction was to make a subclass QNetworkCookieJar but have not made a subclass in Qt/C++ before.

Is there a simple way to store cookies, I am not looking for anything fancy. The cookies just make sure some check boxes are ticked on the login page.

// SLOT that accepts the read data from the webpage
void MainWindow::slotReplyFinished(QNetworkReply *reply){

    if(reply->isFinished()){
        QVariant variantCookies = reply->header(QNetworkRequest::SetCookieHeader);
        QList<QNetworkCookie> cookies = qvariant_cast<QList<QNetworkCookie> >(variantCookies);
        qDebug() << "Cookies reply: " << cookies;
        QNetworkCookie cookie; //Create a cookie



        jar = new QNetworkCookieJar;
        //view->page()->networkAccessManager()->setCookieJar(jar);
        jar->setCookiesFromUrl(cookies, reply->request().url());
        //qDebug() << "Saved cookies: " << jar->getAllCookies();
    }

    qDebug() << "Network reply: " << reply->errorString() << reply->error() << reply->request().url();
 }
Attend answered 20/12, 2012 at 12:2 Comment(0)
Q
6

You will need to subclass QNetworkCookieJar and in that class you should implement your own persistent storage.

class MyNetworkCookieJar : public QNetworkCookieJar {

public: 

bool saveCookiesToDisk() {
// .. my implementation
return true; // if i did
}

bool loadCookiesFromDisk() {
// .. load from disk
return false; // if unable to.
}
}

The sample application from Qt project implements a persistent cookie store, it could be a good starting point for you: http://qt.gitorious.org/qt/qt/trees/4.8/demos/browser

look at cookiejar.h and cookiejar.cpp

Quotha answered 20/12, 2012 at 12:20 Comment(4)
Thanks for the fast reply I will take a look, though I am not entirely sure how to implement that. That looks like all that code needs to go into a header class file, include it in my MainWindow.cpp and then I can call the function right?Attend
Sorry but also the sections of code block // .. my implementation I'm not entirely sure what cookiejar function achieve these two goals?Attend
I think I need to reimplement setCookiesFromUrl() not quite sure how though?Attend
look at the cookiejar.cpp file in the link i posted, it has an implementation, you can just use it.Quotha
A
4

Base of qt example, http://qt.gitorious.org/qt/qt/trees/4.8/demos/browser, i wrote this class that save and use one cookie for me. Perhaps it helps you too. Note that it just save one cookie and not list of cookies.

#include "cookiejar.h"


CookieJar::CookieJar(QObject *parent)
    : QNetworkCookieJar(parent)
    , m_loaded(false)
{
}

void CookieJar::load()
{
    if (m_loaded)
        return;

    QSettings settings;
    settings.beginGroup(QLatin1String("cookies"));
    QList<QNetworkCookie> savedCookies = QNetworkCookie::parseCookies(settings.value("cookies").toByteArray());

    for (int j = 0; j < savedCookies.count(); j++)
        insertCookie(savedCookies.at(j));

    m_loaded = true;
    emit cookiesChanged();
}

void CookieJar::save()
{
    if (!m_loaded)
        return;

    QList<QNetworkCookie> cookies = allCookies();

    QSettings settings;
    settings.beginGroup(QLatin1String("cookies"));
    settings.setValue("cookies", cookies[0].toRawForm());
}

QList<QNetworkCookie> CookieJar::cookiesForUrl(const QUrl &url) const
{
    // This function is called by the default QNetworkAccessManager::createRequest(),
    // which adds the cookies returned by this function to the request being sent.

    CookieJar *that = const_cast<CookieJar*>(this);
    if (!m_loaded)
        that->load();

    return QNetworkCookieJar::cookiesForUrl(url);
}

bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
{
    if (!m_loaded)
        load();

    QNetworkCookieJar::setCookiesFromUrl(cookieList, url);
    save();     //Save cookie permanently in setting file.
    emit cookiesChanged();
    return true;
}
Angulate answered 1/8, 2015 at 11:9 Comment(1)
Check the link that i've shared.Angulate
S
3

@Musa's answer is good but it only saves one cookie. I recommend using the Qt folk's implementation from the old qmlviewer located here: http://code.qt.io/cgit/qt/qt.git/tree/tools/qml/qmlruntime.cpp?h=4.7#n438

Here's the code:

class PersistentCookieJar : public QNetworkCookieJar {
public:
    PersistentCookieJar(QObject *parent) : QNetworkCookieJar(parent) { load(); }
    ~PersistentCookieJar() { save(); }

    virtual QList<QNetworkCookie> cookiesForUrl(const QUrl &url) const
    {
        QMutexLocker lock(&mutex);
        return QNetworkCookieJar::cookiesForUrl(url);
    }

    virtual bool setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
    {
        QMutexLocker lock(&mutex);
        return QNetworkCookieJar::setCookiesFromUrl(cookieList, url);
    }

private:
    void save()
    {
        QMutexLocker lock(&mutex);
        QList<QNetworkCookie> list = allCookies();
        QByteArray data;
        foreach (QNetworkCookie cookie, list) {
            if (!cookie.isSessionCookie()) {
                data.append(cookie.toRawForm());
                data.append("\n");
            }
        }
        QSettings settings;
        settings.setValue("Cookies",data);
    }

    void load()
    {
        QMutexLocker lock(&mutex);
        QSettings settings;
        QByteArray data = settings.value("Cookies").toByteArray();
        setAllCookies(QNetworkCookie::parseCookies(data));
    }

    mutable QMutex mutex;
};
Schexnayder answered 8/7, 2016 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.