3

在 QWebView 中,可以通过 QNetworkAccessManager 设置 QNetworkCookieJar。

QNetworkAccessManager *nam = new QNetworkAccessManager();    
nam->setCookieJar(cookieJar);
webView->page()->setNetworkAccessManager(nam);    

这就像一个魅力。

如何在 Qt5.4 中引入的新 QWebEngine 类中设置 QNetworkCookieJar?

4

1 回答 1

3

我找到了一个解决方案,通过使用 QWebEngineCookieStore 与 QWebEngine 和 QNetworkAccesManager 共享 Cookie。子类 QNetworkCookieJar:

class CookieWebEngine : public QNetworkCookieJar
{
.....
protected:
    // Reimplement this functions to work with your _cookies list;
    bool insertCookie(const QNetworkCookie &cookie);
    bool deleteCookie(const QNetworkCookie &cookie);
    bool updateCookie(const QNetworkCookie &cookie);
    bool validateCookie(const QNetworkCookie &cookie, const QUrl &url) const;
private:
    // Save Chromium Cookies
    QWebEngineCookieStore *_store;
    // Save available cookies
    QList<QNetworkCookie> _cookies;
}

现在,让我们实现一个函数来在文件中加载/保存 cookie:

// Load Chromium Cookies
void CookieWebEngine::loadStore() {
    // Save cookies profile shared
    QWebEngineProfile::defaultProfile()->setPersistentCookiesPolicy(QWebEngineProfile::ForcePersistentCookies);
    _store = WebEngineProfile::defaultProfile()->cookieStore();
    connect(_store, &QWebEngineCookieStore::cookieAdded, this, &CookieWebEngine::handleCookieAdded);
    _store->loadAllCookies();
}
// Load/Save cookies in arraylist in a file
void CookieWebEngine::load() {

    // load cookies and exceptions
    qRegisterMetaTypeStreamOperators<QList<QNetworkCookie> >("QList<QNetworkCookie>");
    const QString location = cookiesDirectory() + COOKIES_FILE;
    QSettings cookieSettings(location, QSettings::IniFormat);
    _cookies = qvariant_cast<QList<QNetworkCookie> >(cookieSettings.value(QLatin1String("cookies")));
    setAllCookies(_cookies);
    // Now user iterate and add it to chromium
    for (auto cookie : _cookies) {
       _store->setCookie(cookie);
    }
    cookieSettings.sync();
}

void CookieWebEngine::save()
{
    QString directory = cookiesDirectory();
    if (!QFile::exists(directory)) {
        QDir dir;
        dir.mkpath(directory);
    }
    const QString location = directory + COOKIES_FILE;
    QSettings cookieSettings(location, QSettings::IniFormat);
    cookieSettings.setValue(QLatin1String("cookies"), QVariant::fromValue<QList<QNetworkCookie>>(_cookies));
    cookieSettings.sync();
}

现在,只需连接并处理从 webview 加载的 cookie:

void CookieWebEngine::handleCookieAdded(const QNetworkCookie &cookie)
{
    if (insertCookie(cookie)) {
        qDebug() << "Handle cookie " << cookie;
    }
}

它对我来说效果很好。现在,我使用 chromium 登录。之后,我将会话 cookie 保存在自定义的 cookiejar 中,并在自定义的 QNetworkAccesManager 中使用它。

于 2016-07-13T12:18:52.717 回答