Pergunta

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();
 }
Foi útil?

Solução

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

Outras dicas

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;
}

@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;
};
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top