在使用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);
}