TasostheGreat
TasostheGreat

Reputation: 432

How do I read headers from a QNetworkReply

How can one read headers for example a cookie out of a QNetworkReply?

Upvotes: 3

Views: 8421

Answers (3)

Quan
Quan

Reputation: 21

I have tried the answer of Evan Shaw, but there is a little mistake. The QNetworkRequest::CookieHeader need change to QNetworkRequest::SetCookieHeader. Because I found it is Set-Cookie in the header of QNetworkReply other than Cookie.

QNetworkReply *reply;
// somehow give reply a value
QVariant cookieVar = reply.header(QNetworkRequest::SetCookieHeader);
if (cookieVar.isValid()) {
    QList<QNetworkCookie> cookies = cookieVar.value<QList<QNetworkCookie> >();
    foreach (QNetworkCookie cookie, cookies) {
        // do whatever you want here
    }
}

Upvotes: 2

Carol
Carol

Reputation: 1930

I just thought to add to the above answer concerning rawHeader

QList<QByteArray> headerList = reply->rawHeaderList();
foreach(QByteArray head, headerList) {
    qDebug() << head << ":" << reply->rawHeader(head);
}

Upvotes: 7

Evan Shaw
Evan Shaw

Reputation: 24547

Consulting the documentation, there are a few methods related to reading headers: header, rawHeader, rawHeaderList, and rawHeaderPairs. For the specific case of getting a cookie, you can use the header method. It would look something like this:

QNetworkReply *reply;
// somehow give reply a value
QVariant cookieVar = reply.header(QNetworkRequest::CookieHeader);
if (cookieVar.isValid()) {
    QList<QNetworkCookie> cookies = cookieVar.value<QList<QNetworkCookie> >();
    foreach (QNetworkCookie cookie, cookies) {
        // do whatever you want here
    }
}

The header method only works for certain HTTP headers, though. In the general case, if there is no QNetworkRequest::KnownHeaders value for the header you want, the rawHeader method is probably the way to go.

Upvotes: 4

Related Questions