forked from bnufree/Hq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
qhttpget.cpp
82 lines (70 loc) · 2.22 KB
/
qhttpget.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
#include "qhttpget.h"
#include <QNetworkAccessManager>
#include <QEventLoop>
#include <QNetworkReply>
#include <QDebug>
#include <QThread>
#include <QTime>
QHttpGet::QHttpGet(const QString& url, QObject *parent) : QObject(parent)
{
mUrl = url;
}
QHttpGet::~QHttpGet()
{
}
QByteArray QHttpGet::getContent(const QString &url)
{
QString wkURL = url.length() != 0 ? url : mUrl;
if(wkURL.length() == 0) return QByteArray();
QNetworkAccessManager *mgr = new QNetworkAccessManager;
QNetworkReply *reply = mgr->get(QNetworkRequest(wkURL));
if(!reply)
{
delete mgr;
return QByteArray();
}
QEventLoop loop; // 使用事件循环使得网络通讯同步进行
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec(); // 进入事件循环, 直到reply的finished()信号发出, 这个语句才能退出
if(reply->error()) return QByteArray();;
//开始解析数据
QByteArray res = reply->readAll();
reply->deleteLater();
mgr->deleteLater();
return res;
}
QByteArray QHttpGet::getContentOfURL(const QString& url)
{
if(url.length() == 0) return QByteArray();
QByteArray res;
QNetworkAccessManager *mgr = new QNetworkAccessManager;
QNetworkReply *reply = mgr->get(QNetworkRequest(url));
if(!reply) goto FUNC_END;
//qDebug()<<__FUNCTION__<<__LINE__<<QThread::currentThread()<<" url:"<<url;
#if 0
{
QEventLoop loop; // 使用事件循环使得网络通讯同步进行
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec(); // 进入事件循环, 直到reply的finished()信号发出, 这个语句才能退出
if(reply->error()) goto FUNC_END;
}
#endif
{
QTime time;
time.start();
while (!reply->isFinished()) {
if(time.elapsed() > 3000) break;
QThread::msleep(100);
}
if(reply->isFinished())
{
//开始解析数据
res = reply->readAll();
}
}
//qDebug()<<__FUNCTION__<<__LINE__<<QThread::currentThread();
FUNC_END:
if(reply)reply->deleteLater();
mgr->deleteLater();
return res;
}