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

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

这就像一种魅力。

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

最佳答案

我找到了一个解决方案,可以使用QWebEngineCookieStore与QWebEngine和QNetworkAccesManager共享Cookies。子类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;
    }
}

它对我来说很好。现在,我使用Chrome登录。之后,我将 session cookie保存在定制的cookiejar中,并在定制的QNetworkAccesManager中使用它。

08-19 07:52