#ifndef URLOP_H
#define URLOP_H
#include <QObject>
#include <qnetworkaccessmanager.h>
#include <qnetworkrequest.h>
#include <qnetworkreply.h>
#include <qurl.h>
#include <qmap.h>
enum OPNUM
{
POST,
GET
};
class urlOp : public QObject
{
Q_OBJECT
public:
explicit urlOp(QObject *parent = 0);
void setOp(const QMap<QString, QString>& requestheader, const QByteArray& opdata, const OPNUM& opnum, QUrl url);
QByteArray getUrlData();
QString getUrlCookie();
int getResponseStatus();
QString getErrorString();
signals:
void getFinished();
void error(int );
private slots:
void replyFinished(QNetworkReply *reply);
private:
QNetworkAccessManager* manager;
QByteArray urlData;
QString header, errString;
int status;
};
#endif // URLOP_H
#include "urlop.h"
#include "common.h"
urlOp::urlOp(QObject *parent) : QObject(parent)
{
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
}
void urlOp::setOp(const QMap<QString, QString>& requestheader, const QByteArray& opdata, const OPNUM& opnum, QUrl url)
{
QNetworkRequest request;
request.setUrl(url);
QMap<QString, QString>::const_iterator iterator;
for(iterator = requestheader.begin(); iterator != requestheader.end(); iterator++)
request.setRawHeader(iterator.key().toLocal8Bit(), iterator.value().toLocal8Bit());
if(opnum == OPNUM::POST)
manager->post(request, opdata);
if(opnum == OPNUM::GET)
manager->get(request);
}
QString urlOp::getUrlCookie()
{
return header;
}
QByteArray urlOp::getUrlData()
{
return urlData;
}
int urlOp::getResponseStatus()
{
return status;
}
QString urlOp::getErrorString()
{
return errString;
}
void urlOp::replyFinished(QNetworkReply *reply)
{
status = reply->error();
errString = reply->errorString();
if((reply != NULL) && (reply->error() == QNetworkReply::NoError))
{
urlData = reply->readAll();
QString tmpheader = reply->rawHeader("Set-Cookie");
//qDebug() << tmpheader;
header = getCookieValue(tmpheader);
emit this->getFinished();
}
else
emit this->error((int)reply->error());
reply->close();
}
common.h相关的是getCookieValue函数
static QString initCookie(const QString& src)
{
return src.split(";").at(0);
}
QString getCookieValue(const QString& src)
{
QString ret, tmp;
QStringList list = src.split("\n");
for(int i = 0; i < list.count(); i++)
{
tmp = initCookie(list.at(i));
if(tmp.right(1) != "=")
ret.append(tmp);
}
return ret;
}