Qt获取Cookie

2016-03-22  本文已影响1638人  stevenjobs

在使用QNetworkAccessManager访问网络时,有时需要管理Cookie信息。Qt的QNetworkCookieJar类实现了一个简单的Cookie容器,但它只在内存中保留Cookie,该类的对象一旦被删除,里面的cookies也被丢弃。如果想存储在本地,必须继承该类然后自己实现存储。文档中有这样一段描述:

This class implements only the basic security recommended by the cookie specifications and does not implement any cookie acceptance policy (it accepts all cookies set by any requests). In order to override those rules, you should reimplement the cookiesForUrl() and setCookiesFromUrl() virtual functions. They are called by QNetworkReply and QNetworkAccessManager when they detect new cookies and when they require cookies.

See also QNetworkCookie, QNetworkAccessManager, QNetworkReply, QNetworkRequest, and QNetworkAccessManager::setCookieJar().

我这里简单的实现了getCookies()setCookies()功能。使用时生成一个NetworkCookieJar对象,再用void QNetworkAccessManager::setCookieJar(QNetworkCookieJar * cookieJar)设置一下即可。

// networkcookiejar.h
#ifndef NETWORKCOOKIEJAR_H
#define NETWORKCOOKIEJAR_H

#include <QNetworkCookie>
#include <QNetworkCookieJar>

class NetworkCookieJar : public QNetworkCookieJar
{
public:
    NetworkCookieJar();

    QList<QNetworkCookie> getCookies();
    void setCookies(const QList<QNetworkCookie>& cookieList);
};

#endif // NETWORKCOOKIEJAR_H

// networkcookiejar.cpp
#include "networkcookiejar.h"

NetworkCookieJar::NetworkCookieJar()
{
}

QList<QNetworkCookie> NetworkCookieJar::getCookies()
{
    return allCookies();
}

void NetworkCookieJar::setCookies(const QList<QNetworkCookie>& cookieList)
{
    if(this == NULL) {
        return;
    }
    setAllCookies(cookieList);
}
上一篇下一篇

猜你喜欢

热点阅读