2

Besically, I post my username and password to a site, say http://example.org/signup.asp. Then I get cookies from it, which I wanna save it in qnam_, an object of QNetworkAccessManager.

Problem 1

The first issue is, after saving the cookies in reply_'s corresponding url, say say http://example.org/signup.asp, I just cannot retrieve it back via http://example.org/ or http://example.org/something_else.

auto cookies = qvariant_cast<QList<QNetworkCookie>>(reply_->header
  (QNetworkRequest::SetCookieHeader));
auto cookieJar = new QNetworkCookieJar(&qnam_);

// qDebug() outputs "http://example.org/sign.asp"
qDebug() << reply_->request().url();

// assert won't fire, which means "one or more cookies are set for url"
assert(cookieJar->setCookiesFromUrl(cookies, reply_->request().url()));
qnam_.setCookieJar(cookieJar);

// qDebug() outputs nothing, but "()", why???
qDebug() << qnam_.cookieJar()->cookiesForUrl(QUrl("http://example.org"));

Problem 2

The second one is even I set cookies in the "root hostname", say http://example.org/, I still cannot retrieve it via the same url.

assert(cookieJar->setCookiesFromUrl(cookies, QUrl("http://example.org")));
qnam_.setCookieJar(cookieJar);

// Still get nothing from it.
qDebug() << qnam_.cookieJar()->cookiesForUrl(QUrl("http://example.org"));

Note that I've checked the QT HTTP Post issue when server requires cookies and How do I save cookies with Qt?, which doesn't work out I think.

Any ideas? Thanks!

Community
  • 1
  • 1
Qi W.
  • 706
  • 9
  • 21
  • I am having issues with this as well, and am quite disappointed no one has answered yet. I think part of the issue is, that the Cookie can have a "path", and I believe you have to request cookies from a URL within that path, so if you set for "www.example.com" and the cookie has a path "/somePlace/", then your cookies will only show up if you call cookiesForUrl("www.example.com/somePlace"). By the way, if you assign the cookie jar to the networkManager before making requests, it seems to fill the cookies on its own. If I figure out, how I can sign into a web-app +keep the session I will answer – smoothware Oct 12 '16 at 18:49

1 Answers1

0

I got this working using the following solution:

in the function callback for QNetworkReply::finished I add a cookie

QNetworkCookie cookie("mycookie", mycookiedata.toUtf8());
QList<QNetworkCookie> cookies;
cookies.append(cookie);
mCookieJar.setCookiesFromUrl(cookies, reply->url());