T
T
terminator-light2018-05-02 17:55:26
Qt
terminator-light, 2018-05-02 17:55:26

How to send request headers Cookie in Qt?

mainwindow.h

private:
    QList<QNetworkCookie> cookies;

in constructor:
cookie.setName("visible");
    cookie.setValue("0");
    cookie.setDomain("site.ru");
    cookie.setPath("/dev/mobile");
    cookie.setExpirationDate(QDateTime().addYears(9999));

    cookies << cookie;

method that sends a request with cookies:
void MainWindow::sendRequest(const QString& urlString){
    log("sendRequest");
    QTimer timer;
    timer.setInterval(3000);
    timer.setSingleShot(true);

    QEventLoop loop;
    currentUrlString = urlString;
    url->setUrl(urlString);
    request->setUrl(*url);

    request->setHeader(QNetworkRequest::CookieHeader, qVariantFromValue(cookies));
    qDebug() << "Cookie:" << request->header(QNetworkRequest::CookieHeader).toList();
    QNetworkReply* reply  = manager->get(*request);
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    QObject::connect(&timer, &QTimer::timeout, reply, &QNetworkReply::abort);
    timer.start();
    loop.exec();
}

When I check like this
qDebug() << "Cookie:" << request->header(QNetworkRequest::CookieHeader).toList();

the list is empty, it turns out that cookies are not being sent

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2018-05-02
@terminator-light

Look closely at what returns QVariant::toList.
You need to convert explicitly:

request->header(QNetworkRequest::CookieHeader).value<QList<QNetworkCookie>>()

PS
This construct is obsolete: qVariantFromValue. Use QVariant::fromValue().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question