PDA

View Full Version : qnetwork manager does not allow redirection?



JeanC
17th March 2011, 10:36
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)


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();
};



//-------------------------------------------------------------------------------
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;
}


Use as:


QCoreApplication a(argc, argv); // needed for qApp
Http h;
QString S = h.Get("http://someurl");

frankiefrank
15th May 2011, 10:59
Hi JeanC. I was dealing with the same issue right now.

You can check the reply object to see if the status code is 301 (redirect). If so there's a redirection url attribute that would be set to the target URL.



QVariant replyStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute );

//! If needs to redirect - download from updated url
if (replyStatus == 301)
{
QString redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttrib ute).toString();

// HERE - just use the url for creating a new request