Chinaunix首页 | 论坛 | 博客
  • 博客访问: 530214
  • 博文数量: 71
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 159
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-13 12:37
个人简介

aaaaaaaaa

文章分类

全部博文(71)

文章存档

2013年(71)

我的朋友

分类: 嵌入式

2013-07-26 00:51:24

 2  accepted

I use this to get a cookie:

SomeDialog::SomeDialog(QWidget *parent)
    : QDialog(parent)
        , urlSearch("")
    , urlCookie("")
{
    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 cookies = qvariant_cast>(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 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.

阅读(775) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~