Accessing headers/cookies in WebSockets handshake request
-
Hi. I'm playing with Websockets Simplechat example from here QT Simplechat:
It's works correctly but how can I access cookies?
The docs says that we can access/use it Mozilla MDN
Also, common headers like User-Agent, Referer, Cookie, or authentication headers might be there as well.
And I see that Mozilla (Opera) transfers Cookie header.
-
@Cocojambo said in Accessing headers/cookies in WebSockets handshake request:
QT Simplechat:
In that example, you can have the QWebSocket from every connection
QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());
so with QWebSocket::request() you can have the QNetworkRequest for such connection
and ultimately you'll get the headers from that request:QNetworkRequest::header(QNetworkRequest::KnownHeaders header)
QNetworkRequest::rawHeader(const QByteArray &headerName) -
@Pablo-J-Rogina
Thank you, your answer helped me. Something like this returns all cookies as raw string.QNetworkRequest rq = pSocket->request(); QByteArray h = rq.rawHeader("Cookie"); qDebug() << QString::fromUtf8(h);
Could you also advice how to iterate all cookies from the header?
QVariant hdr = rq.header(QNetworkRequest::CookieHeader);
qDebug() << hdr
returnsQVariant(QList<QNetworkCookie>, )
and in debugger I see that it contains several items (the same qty as browser sends). -
@Cocojambo said in Accessing headers/cookies in WebSockets handshake request:
qDebug() << hdr returns QVariant(QList<QNetworkCookie>, )
Well, your "problem" now turned into iterating a list of QNetworkCookie items... some pseudo-code:
foreach (QNetworkCookie cookie, hdr) { qDebug() << cookie.toRawForm(); }
-
Accidentally found needed code in QT sources. It returns all the cookies one by one.
QVariant hdr = rq.header(QNetworkRequest::CookieHeader); QList<QNetworkCookie> cookies = qvariant_cast<QList<QNetworkCookie> >(hdr); QList<QNetworkCookie>::ConstIterator it = cookies.begin(), end = cookies.end(); for ( ; it != end; ++it) { qDebug() << it->name(); }