如何在 QML 中使用 QWebview 设置 cookie? [英] How to set cookie with QWebview in QML?

查看:52
本文介绍了如何在 QML 中使用 QWebview 设置 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 QML 中使用 QWebView.我想显示需要身份验证的网站.数据应通过标准 cookie 传递.有什么帮助吗?额外的链接或示例会很棒.

I am using QWebView in QML. I want to show web site that needs authentication. Data should be passed via standard cookie. Any help? Additional link or example would be great.

提前致谢.

推荐答案

默认情况下,webkit 使用的默认 QNetworkAccessManager 有自己的(非持久性)cookie jar,也就是 QNetworkCookieJar.

By default, the default QNetworkAccessManager used by webkit have its own (non-persistent) cookie jar, aka QNetworkCookieJar.

这将在 QWebPage 的生命周期内处理 cookie 的发送和接收.

This will handle the sending and receiving of cookies during the life span of a QWebPage.

要在多个页面中保留同一个 cookie jar,您必须:

To keep the same cookie jar across multiple pages, you have to:

  1. 创建一个 QNetworkCookieJar 的实例,可能是子类化让它持久化
  2. 将这个 cookie jar 附加到每个新的创建 QWebPage

保存到设置的持久性 cookie jar 示例:

Example of a persistent cookie jar saved to settings:

class PersistentCookieJar : public QNetworkCookieJar {
public:
    PersistentCookieJar(QObject *parent) : QNetworkCookieJar(parent) { load(); }
    ~PersistentCookieJar() { save(); }

public:
    void save()
    {
        QList<QNetworkCookie> list = allCookies();
        QByteArray data;
        foreach (QNetworkCookie cookie, list) {
            if (!cookie.isSessionCookie()) {
                data.append(cookie.toRawForm());
                data.append("
");
            }
        }
        QSettings settings;
        settings.setValue("Cookies",data);
    }

    void load()
    {
        QSettings settings;
        QByteArray data = settings.value("Cookies").toByteArray();
        setAllCookies(QNetworkCookie::parseCookies(data));
    }
};

使用方法:

QWebView* vw = new QWebView(this);
PersistenCookieJar* jar = new PersistenCookieJar(this);
vw->page()->networkAccessManager()->setCookieJar(jar);  // the jar is reparented to the page
jar->setParent(this);  // reparent to main widget to avoid destruction together with the page

这篇关于如何在 QML 中使用 QWebview 设置 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆