开发者

How can I load session information into qtwebkit?

I am building a specialized browser based on Qtwebkit. I would like to save the session information when logging into authenticate开发者_如何学运维d websites and load this information again when I restart the browser. How can I do this?


Most websites use cookies to store session id. You can save cookies using
QList<QNetworkCookie> QNetworkCookieJar::allCookies () const
and load them back using
void QNetworkCookieJar::setAllCookies(const QList<QNetworkCookie> & cookieList)
You can get QNetworkCookieJar using
QNetworkCookieJar * QNetworkAccessManager::cookieJar () const
and you can get QNetworkAccessManager being used by QWebPage using
QNetworkAccessManager * QWebPage::networkAccessManager () const

Session id can be also stored as part of url or in the hidden form field on the page. If the site uses the former it's enough to save the url and if it uses the latter you have to save the page itself, too.

The task gets more complicated now, when the Web Storage could be used. If a site makes use of the web storage you should take care of saving and restoring it in addition to all of the above data. You can set the location for offline storage using
void QWebSettings::setOfflineStoragePath(const QString & path)
and get it using
QString QWebSettings::offlineStoragePath ()
You might get some more information on webkit-qt mailing list and on #qtwebkit IRC channel on freenode.net


You can refer to QNetworkCookieJar virtual member function bool CookieHandler::setCookiesFromUrl (const QList<QNetworkCookie> & cookieList, const QUrl & url) can be used to save cookies into your own persistent storage. For example,

bool CookieHandler::setCookiesFromUrl (const QList<QNetworkCookie> & cookieList, const QUrl & url) {
    foreach(QNetworkCookie i, cookieList) {
    // probably don't want to store session cookies
    if (!i.isSessionCookie()) {
      // save the cookie to own storage format
    }
}
return true;

}

protected member functionvoid QNetworkCookieJar::setAllCookies ( const QList<QNetworkCookie> & cookieList ) is used to restore cookies from your own storage to QNetworkCookieJar since QNetworkCookieJar does not implement permanent storage: it only keeps the cookies in memory. example code,

void CookieHandler::setAllCookiestoJar() {
    // retrieve cookies from local database
    QList<QNetworkCookie> cookieList = this->getCookiesFromLocalDB();
    this->setAllCookies(cookieList);
    // check if they are correctly loaded
    QList<QNetworkCookie> cookieList_tmp = this->allCookies();
    foreach(QNetworkCookie i, cookieList_tmp)
      qDebug() << i.toRawForm(QNetworkCookie::Full);

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜