QT HTTP Post issue when server requires cookies

倾然丶 夕夏残阳落幕 提交于 2019-12-04 05:19:11

I use this to get a cookie:

SomeDialog::SomeDialog(QWidget *parent)
    : QDialog(parent)
        , urlSearch("www.someotherurlyoumightneed.com")
    , urlCookie("www.urltogetcookie.from")
{
    ui.setupUi(this);

    //manager is a QNetworkAccessManager
    manager.setCookieJar(new QNetworkCookieJar);
    connect(&manager, SIGNAL(finished(QNetworkReply*)),
        SLOT(slotReplyFinished(QNetworkReply*)));

    //this is a QNetworkRequest
    //here i tell how the post methods are encoded
    searchReq.setUrl(urlSearch);
    searchReq.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");

    //get cookie
    manager.get(QNetworkRequest(urlCookie));
    lblStatus->setText("Getting cookie");
}

void SomeDialog::slotReplyFinished(QNetworkReply* reply){
    reply->deleteLater();

    if(reply->error() != QNetworkReply::NoError){
        QMessageBox::warning(this,QString(), tr("Error while downloading information!\n%1").arg(reply->errorString()));

        return;
    }

    //Here i check if there is a cookie for me in the reply and extract it
    QList<QNetworkCookie> cookies = qvariant_cast<QList<QNetworkCookie>>(reply->header(QNetworkRequest::SetCookieHeader));
    if(cookies.count() != 0){
        //you must tell which cookie goes with which url
        manager.cookieJar()->setCookiesFromUrl(cookies, urlSearch);
    }

    //here you can check for the 302 or whatever other header i need
    QVariant newLoc = reply->header(QNetworkRequest::LocationHeader);
    if(newLoc.isValid()){
        //if it IS a reloc header, get the url it points to
        QUrl url(newLoc.toString());
        _req.setUrl(url);
        _pendingReq.insert(_manager.get(_req));
        return;
    }

    //if you have multiple urls you are waiting for replys
    //you can check which one this one belongs to with
    if(reply->url() == urlSearch){
        //do something
    }
}

void SomeDialog::slotSearch(){
    //Here we set the data needed for a post request
    QList<QNetworkCookie> cookies = manager.cookieJar()->cookiesForUrl(urlSearch);
    for(auto it = cookies.begin(); it != cookies.end(); ++it){
        searchReq.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(*it));
    }

    QUrl post;
    post.addQueryItem("firstParameter", s);
    post.addQueryItem("secondParameter", "O");
    QByteArray ba;
    ba.remove(0,1); //must remove last &

    searchReq.setUrl(urlSearch);
    pendingReq.insert(manager.post(searchReq, ba));
}

Hope this helps.

I think cookies are linked to the URLs they are obtained from. So in your second POST with a different URL, the cookies from the first POST are not sent with the request.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!