00001
00002
00003
00004 #include <stdint.h>
00005 #include <unistd.h>
00006
00007
00008 #include <qapplication.h>
00009 #include <qurloperator.h>
00010 #include <qdeepcopy.h>
00011
00012
00013 #include "urlfetcher.h"
00014
00015 URLFetcher::URLFetcher(const QString &url) :
00016 op(new QUrlOperator(url)),
00017 state(QNetworkProtocol::StInProgress)
00018 {
00019 connect(op, SIGNAL( finished(QNetworkOperation*)),
00020 this, SLOT( Finished(QNetworkOperation*)));
00021 connect(op, SIGNAL( data(const QByteArray&, QNetworkOperation*)),
00022 this, SLOT( Data(const QByteArray&, QNetworkOperation*)));
00023 op->get();
00024 }
00025
00026 void URLFetcher::deleteLater(void)
00027 {
00028 disconnect();
00029 if (op)
00030 {
00031 op->disconnect();
00032 op->deleteLater();
00033 op = NULL;
00034 }
00035 }
00036
00037 void URLFetcher::Finished(QNetworkOperation *op)
00038 {
00039 state = op->state();
00040 }
00041
00042 void URLFetcher::Data(const QByteArray &data, QNetworkOperation *op)
00043 {
00044 if (!data.isNull())
00045 {
00046 uint64_t beg = buf.size();
00047 buf.resize(beg + data.size());
00048 memcpy(&buf[beg], data.data(), data.size());
00049 }
00050 state = op->state();
00051 }
00052
00053 QString URLFetcher::FetchData(const QString &url, bool inQtThread)
00054 {
00055 URLFetcher *instance = new URLFetcher(url);
00056
00057 while (instance->state == QNetworkProtocol::StWaiting ||
00058 instance->state == QNetworkProtocol::StInProgress)
00059 {
00060 if (inQtThread)
00061 qApp->processEvents();
00062
00063 usleep(10000);
00064 }
00065
00066 QString ret = QString::null;
00067 if (instance->state == QNetworkProtocol::StDone)
00068 {
00069 ret = QDeepCopy<QString>(
00070 QString::fromUtf8((const char*) &instance->buf[0],
00071 instance->buf.size()));
00072 }
00073
00074 instance->deleteLater();
00075
00076 return ret;
00077 }