Hello,
I made a very simple class to fetch a page as a string synchronous, but I saw that when there is a http redirect, qnetworkmanager just returns 'this page has moved'. Is there a solution for this?
This is my class, please feel free to ciritize it. (except the use of upper/lowercase, I'm still getting used to / muttering about Qt's conventions)
{
Q_OBJECT
QNetworkAccessManager *manager;
private slots:
void replyFinished(QNetworkReply *);
public:
bool ready, error;
int timeout;
Http();
~Http();
};
class Http : public QObject
{
Q_OBJECT
QNetworkAccessManager *manager;
private slots:
void replyFinished(QNetworkReply *);
public:
bool ready, error;
int timeout;
QString Reply;
QString Get(QString);
Http();
~Http();
};
To copy to clipboard, switch view to plain text mode
//-------------------------------------------------------------------------------
Http::~Http()
{
delete manager;
}
//-------------------------------------------------------------------------------
Http::Http()
{
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
timeout = 60;
Reply = "";
}
//-------------------------------------------------------------------------------
void Http::replyFinished(QNetworkReply *reply)
{
error = reply->error();
Reply = error ? "" : reply->readAll();
ready = true;
reply->deleteLater();
}
//-------------------------------------------------------------------------------
{
manager->get(QNetworkRequest(qrl));
ready = false;
QTime cur
= QTime::currentTime().
addSecs(timeout
);
while (!ready
&& QTime::currentTime() < cur
) qApp->processEvents();
return Reply;
}
//-------------------------------------------------------------------------------
Http::~Http()
{
delete manager;
}
//-------------------------------------------------------------------------------
Http::Http()
{
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
timeout = 60;
Reply = "";
}
//-------------------------------------------------------------------------------
void Http::replyFinished(QNetworkReply *reply)
{
error = reply->error();
Reply = error ? "" : reply->readAll();
ready = true;
reply->deleteLater();
}
//-------------------------------------------------------------------------------
QString Http::Get(QString S)
{
QUrl qrl(S);
manager->get(QNetworkRequest(qrl));
ready = false;
QTime cur = QTime::currentTime().addSecs(timeout);
while (!ready && QTime::currentTime() < cur)
qApp->processEvents();
return Reply;
}
To copy to clipboard, switch view to plain text mode
Use as:
Http h;
QString S
= h.
Get("http://someurl");
QCoreApplication a(argc, argv); // needed for qApp
Http h;
QString S = h.Get("http://someurl");
To copy to clipboard, switch view to plain text mode
Bookmarks