-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmyhttp.cpp
96 lines (82 loc) · 2.26 KB
/
myhttp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "myhttp.h"
void MyHttp::EventHandle(const QString &key)
{
auto iter = _Handles.find(key);
if (iter != _Handles.end()){
auto &handlers= iter->second;
if (handlers())
_Handles.erase(iter);
}
return;
}
MyHttp::MyHttp(QObject *parent) :
QObject(parent),
_Http(std::make_shared<QQHttp>(parent)),
_reply(nullptr),
_requests(std::make_shared<std::list<MyHttp::__request> >()),
_timer(std::make_shared<QTimer>())
//_httpBuf(std::make_shared<QBitArray>())
{
connect(_timer.get(), SIGNAL(timeout()), this, SLOT(doRequest()));
_timer->start(500);
connect(_Http.get(), SIGNAL(readyRead(QNetworkReply *)), this,
SLOT(onHttpFinished(QNetworkReply *)));
}
bool MyHttp::request(const QString &url, const MyHttp::CallBack &cb, MyHttp::Method method, const QByteArray *buf)
{
return request(QNetworkRequest(url), cb, method, buf);
}
bool MyHttp::request(const QNetworkRequest &req, const MyHttp::CallBack &cb,
MyHttp::Method method, const QByteArray *buf)
{
if (buf == nullptr)
_requests->push_back({req, cb, method, QByteArray()});
else _requests->push_back({req, cb, method, *buf});
return true;
}
bool MyHttp::doRequest()
{
if(_requests->empty())
return false;
auto request = _requests->front();
auto req = request.req;
auto method = request.method;
auto cb = request.cb;
_requests->pop_front();
if(req.url().isValid()){
auto iter = _Handles.find(req.url().toString());
if (iter != _Handles.end()){
return false;
}else{
_Handles[req.url().toString()] = cb;
}
if(method == GET){
_Http->get(req);
}else if (method == POST){
auto buf = request.buf;
_Http->post(req, buf);
}else{
return false;
}
return true;
}
return true;
}
void MyHttp::setPollTime(unsigned int time)
{
_timer->stop();
_timer->start(time);
}
void MyHttp::setReply(QNetworkReply *r)
{
_reply = r;
}
QNetworkReply *MyHttp::getReply()
{
return _reply;
}
void MyHttp::onHttpFinished(QNetworkReply *reply)
{
setReply(reply);
EventHandle(QString(reply->url().toString()));
}