如何在Qt中使用cookies - 小众知识

如何在Qt中使用cookies

2014-07-18 15:27:38 苏内容
  标签: Qt/cookies
阅读:6788

 Overview

A cookie, also known as a web cookie, browser cookie, and HTTP cookie, is a piece of text stored by a user's web browser. A cookie can be used for authentication, storing site preferences, shopping cart contents, the identifier for a server-based session, or anything else that can be accomplished through storing text data. A cookie consists of one or more name-value pairs containing bits of information, which may be encrypted for information privacy and data security purposes. The cookie is sent as an HTTP header by a web server to a web browser and then sent back unchanged by the browser each time it accesses that server.
Code

The Qt Network module offers the class QNetworkCookieJar which can be used with QNetworkAccessManager to manage cookies in Qt applications. The following class will show you how to send a post request to a URL and read the cookies stored in the header.

#ifndef COOKIESHANDLER_H
#define COOKIESHANDLER_H
#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkCookieJar>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QDebug>
 
class cookiesHandler: public QObject{
    Q_OBJECT
 
public:
    cookiesHandler(QObject *parent = 0) : QObject(parent){
        mManager = new QNetworkAccessManager(this);
        mManager->setCookieJar(new QNetworkCookieJar(this));
        connect(mManager, SIGNAL(finished(QNetworkReply*)), SLOT(replyFinished(QNetworkReply*)));
    }
 
    void sendPostRequest(const QUrl &url, const QByteArray &data){
        mUrl = url;
        QNetworkRequest r(mUrl);
        mManager->post(r, data);
    }
 
    virtual ~cookiesHandler(){}
 
private slots:
    void replyFinished(QNetworkReply *reply){
        if (reply->error() != QNetworkReply::NoError){
            qWarning() << "ERROR:" << reply->errorString();
            return;
        }
 
        QList<QNetworkCookie>  cookies = mManager->cookieJar()->cookiesForUrl(mUrl);
        qDebug() << "COOKIES for" << mUrl.host() << cookies;
    }
 
private:
    QNetworkAccessManager *mManager;
    QUrl mUrl;
};
 
 
#endif // COOKIESHANDLER_H

The previous class can be used as follow:

QUrl url("https://yourwebsite.com"); // https and http are both allowed.
QByteArray postData;
postData.append("username=myUsername&password=myPAss&hiddenFields=ifAny");
c.sendPostRequest(url, postData);

The cookie can be sent back to the server with another request in this way:

QList<QNetworkCookie>  cookies = mManager->cookieJar()->cookiesForUrl(mUrl);
QVariant var;
var.setValue(cookies);
 
QNetworkRequest r(QUrl("http://www.developer.nokia.com/Profile/"));
r.setHeader(QNetworkRequest::CookieHeader, var);
mManager->get(r);
扩展阅读
相关阅读
© CopyRight 2010-2021, PREDREAM.ORG, Inc.All Rights Reserved. 京ICP备13045924号-1