How do I save cookies with Qt?

Kal picture Kal · Dec 20, 2012 · Viewed 9.3k times · Source

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

Answer

Ahmad Mushtaq picture Ahmad Mushtaq · Dec 20, 2012

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