QT HTTP Post服务器需要Cookie时出现问题 [英] QT HTTP Post issue when server requires cookies

查看:2251
本文介绍了QT HTTP Post服务器需要Cookie时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试这整天,没有成功。请帮助解决问题。在Google上,我发现很多用户都遇到了这个问题,但没有找到解决方案。

I have been trying this whole day with no success. Please help in solving the issue. On googling I found many users had this issue but nowhere I could find a solution.

我试图在QT C ++&我已经尝试这样做在python (我的问题不是一个python问题,所以Qt专业人员请帮助)..我知道,我处理cookies和所有的错误,所以请帮助。请提供可能的解决方案。

I am trying to do HTTP post in QT C++ & I have already tried doing that in python (My question is not a python question, so Qt pros please help).. I know, I am somewhere wrong in handling cookies and all, so please help. Please provide probable solutions.

在python中,代码干净简单。我已经删除了错误处理和所有额外的事情,使它很简单。

In python, code is clean and simple. I have stripped error handling and all extra things to make it simple.

url = 'http://www.example.com/'
data = 'username=abc&password=passwd'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
usock = opener.open(url, data)
#>>>>>> NOW, I have the cookiejar <<<<<<<<<

opener.addheaders = [('Referer','http://www.example.com/xyz.php'),('User-Agent','Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20091020 Ubuntu/9.10 (karmic) Firefox/3.5.3 GTB7.0')]
data_to_send = 'ABCDEFGH'
url_send = "http://www.example.com/xyz.php"
send = opener.open(url_send,data_to_send)

我做的QT等价: -

The QT Equivalent I made:-

void SmsSender::sendToMyCantos()
{
    manager = new QNetworkAccessManager(this);
    manager->setCookieJar(new QNetworkCookieJar(manager));
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));
    request.setUrl(QUrl("http://www.mycantos.com"));
    postData.append("username=abc&password=passwd");
    manager->post(request,postData);
    //>>>>>> So, I feel that I have CookieJar now to make POST <<<<<<<

    request.setRawHeader("Referer","http://www.example.com/xyz.php");
    request.setRawHeader("User-Agent","Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20091020 Ubuntu/9.10 (karmic) Firefox/3.5.3 GTB7.0");

    postData.clear();
    postData.append("ABCDEFGH");
    request.setUrl(QUrl("http://www.example.com/xyz.php"));

    manager->post(request,postData);
}



现在问题是我不能在QT中做同样的事情。我遇到的问题:

Now the issue is that I am not able to do the same in QT. Problems I am facing:


  1. 处理Cookie

  2. 处理重定向(HTTP 302)

  3. 保留Cookie以使将来的POST

这一切都是在python中自动完成的。
下面的代码不直接相关,但我编码这允许重定向在POST ..代码非常类似于我用来做它的链接。

All this is done automagically in python. Below, the code is not directly related, but I coded this to allow redirects in the POST.. The code is very similar to the link I used to make it..

QUrl SmsSender::redirectUrl(const QUrl& possibleRedirectUrl,
                               const QUrl& oldRedirectUrl) const {
        //Checking infinite resursions
        QUrl redirectUrl;
        if(!possibleRedirectUrl.isEmpty() &&
           possibleRedirectUrl != oldRedirectUrl) {
                redirectUrl = possibleRedirectUrl;
        }
        return redirectUrl;
}

void SmsSender::replyFinished(QNetworkReply *reply)
{
    QVariant possibleRedirectUrl =
             reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    QVariant data_size = reply->header(QNetworkRequest::ContentLengthHeader);
    qDebug()<<data_size.toFloat();
    qDebug()<<manager->cookieJar()->cookiesForUrl(QUrl("http://www.example.com"));

    /* We'll deduct if the redirection is valid in the redirectUrl function */
    _urlRedirectedTo = this->redirectUrl(possibleRedirectUrl.toUrl(),
                                         _urlRedirectedTo);

    /* If the URL is not empty, we're being redirected. */
    if(!_urlRedirectedTo.isEmpty()) {
            QString text = QString("SmsSender::replyFinished: Redirected to ")
                                  .append(_urlRedirectedTo.toString());
    qDebug(text.toAscii());

    // Do again in case we have more redirections

    this->_qnam->get(QNetworkRequest(_urlRedirectedTo));
    }
    else
    {
        QString text = QString("SmsSender::replyFinished: Arrived to ")
                                  .append(reply->url().toString());
        qDebug(text.toAscii());
        _urlRedirectedTo.clear();
    }

}

QNetworkAccessManager* SmsSender::createQNAM() {
        QNetworkAccessManager* qnam = new QNetworkAccessManager(this);
        /* We'll handle the finished reply in replyFinished */
        connect(qnam, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(replyFinished(QNetworkReply*)));
        return qnam;
}


推荐答案

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));
}

希望这有帮助。

这篇关于QT HTTP Post服务器需要Cookie时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆