1.添加QNetwork模块:
a.Qt Creator中打开.pro文件添加QT+=Network;
b.VS_Qt中项目属性中Qt Project Settings中Qmodules中勾选”QNetwork library“
2.添加头文件:
#include <QNetworkAccessManager> #include <QNetworkCookieJar> #include <QNetworkRequest> #include <QNetworkReply>
3.获取Post的cookies
//url为请求网址,content为请求内容,即传递的参数,allcookies应该定义为全局变量,这里为了演示,则定义为局部变量
void NuistMoney::PostLToNet(QString url ,QString content) { QByteArray _content = content.toUtf8(); int _contentLength = content.length(); QNetworkRequest req; req.setUrl(QUrl(url)); req.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded"); req.setHeader(QNetworkRequest::ContentLengthHeader,_contentLength); QNetworkAccessManager nManager; QNetworkReply* getreply=nLManager.post(req,_content); QEventLoop loop; //下载完成后,直接退出子进程 connect(getreply, SIGNAL(finished()), &loop, SLOT(quit())); //子进程开始运行 loop.exec(); //读取所有获取到的网页内容 QTextCodec *codec = QTextCodec::codecForName("utf8");//使用utf8编码,这样才可以显示中文 QString data= codec->toUnicode(getreply->readAll());//获取网页的所有数据 QList<QNetworkCookie> allcookies=nManager.cookieJar()->cookiesForUrl(QUrl(murl)); }
4.使用cookies:
//根据获取的cookies直接获取murl网址指定的信息
QString NuistMoney::GetToAllNet(QString murl) { //转换cookies成QVariant QVariant var; var.setValue(allcookies); //设置QNetworkRequest的网址和cookies QNetworkRequest req; req.setUrl(QUrl(murl)); req.setHeader(QNetworkRequest::CookieHeader,var); //通过QNetworkAccessManager对象获取网页内容 QNetworkAccessManager nManager; QNetworkReply* getreply=nManager.get(req); //创建一个子进程,以便于提供时间给QNetworkAccessManager对象下载完网页内容 QEventLoop loop; //下载完成后,直接退出子进程 connect(getreply, SIGNAL(finished()), &loop, SLOT(quit())); //子进程开始运行 loop.exec(); //读取所有获取到的网页内容 QTextCodec *codec = QTextCodec::codecForName("utf8");//使用utf8编码,这样才可以显示中文 QString data= codec->toUnicode(getreply->readAll());//获取网页的所有数据 return data; }