I'm trying to get the HTML source of a webpage online, my code is as follows:
void Helper::start()
{
QString url = "http://www.youtube-mp3.org/get?video_id=PnL4Z0ebcBc";
QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request;
request.setUrl(QUrl(url));
request.setRawHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0;)");
QNetworkReply *reply = manager->get(request);
QObject::connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));
QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
}
void Helper::onFinished()
{
QIODevice * content = static_cast<QIODevice*>(QObject::sender());
QString html = content->readAll();
content->deleteLater();
qDebug() << html; // It's empty!!
}
void Helper::onError(QNetworkReply::NetworkError err)
{
qDebug() << "Starting On Error ....";
QIODevice * content = static_cast<QIODevice*>(QObject::sender());
QString error = content->errorString();
content->deleteLater();
qDebug() << error;
}
The html
string is empty, I can't figure out why!
When I change the URL to Google's, it works, what's wrong? ( As I'm not getting any kind of error )
The reason you are getting empty response is because of the url redirection which you aren't catching.
The url mentioned in your code http://www.youtube-mp3.org/get?video_id=PnL4Z0ebcBc
gets redirected to http://www.youtube-mp3.org/?e=session_expired&t#v=PnL4Z0ebcBc
. So either you supply the redirected url in your code, or take some effort and handle the redirects.
First of all it's better to use the QNetworkReply
class instead of QIODevice
class for this purpose.
QNetworkReply* content= qobject_cast<QNetworkReply*>(sender());
Then check if are being redirected using the QNetworkReply::attribute
method.
content->attribute(QNetworkRequest::RedirectionTargetAttribute)
I have written the working code, but I don't see the need to share it here since I have already told the key things. ;)
Also, I suggest you take a look at this.