How to use http cookies with Qt

How to use http cookies with Qt

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);

Comments

(no comments yet)

This page was last modified on 11 October 2012, at 04:17.
198 page views in the last 30 days.

你可能感兴趣的:(How to use http cookies with Qt)