c++qtqnetworkaccessmanagerqtnetworkqnetworkreply

How to add a token when I use the GET method in Qt?


I would like to add a token in my GET request in C++/Qt.

This is my GET / download method :

QNetworkReply* DownloadManager::doDownload(const QUrl &url)
{
    QNetworkRequest request(url);
    QNetworkReply *reply = m_manager.get(request); // m_manager is a QNetworkAcessManager

    return reply;
}

Solution

  • The tokens are sent as part of the request header, so for that case we use the setRawHeader() method:

    void QNetworkRequest::setRawHeader(const QByteArray &headerName, const QByteArray &headerValue)

    Sets the header headerName to be of value headerValue. If headerName corresponds to a known header (see QNetworkRequest::KnownHeaders), the raw format will be parsed and the corresponding "cooked" header will be set as well.

    In the case of the token we use the following:

    request.setRawHeader(QByteArray("Authorization"), QByteArray("Token your_token"));