PDA

View Full Version : QNetworkAccessManager.get(QNetworkRequest) not working.. :(



matthieunc
23rd July 2011, 08:29
Hey there, I'm completely new to this forum! I'm coming here because I'm having an issue in my Qt code, and my beginner skills aren't helping me a lot...

I'm trying to send a request to get the content of a tumblr blog, at "kauritree.tumblr.com/api/read". The file I should get is an XML file, so I created a class that is in charge of downloading the file, and transforming it in whatever I want. I just cant get the QNetworkAccessManager.get(request) to be working... and I dont know why. The GET request is not even sent (I checked using Wireshark)... Thank you for your help!

here is my code:

main.cpp:


QUrl qUrl;
qUrl.setUrl("http://kauritree.tumblr.com/api/read/");
ListeXml listeXml;
listeXml.downloadd(qUrl);


my ListeXml.cpp


ListeXml::ListeXml(QObject *parent) :
QObject(parent)
{
}

QString ListeXml::downloadd(QUrl url)
{
DownloadManager manager;
manager.doDownload(url.toString());
}


DownloadManager.cpp


DownloadManager::DownloadManager() //Constructor
{
QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)),SLOT(downloadFini shed(QNetworkReply*)));
}

void DownloadManager::doDownload(QString Url)
{
QUrl url;
url.setUrl(Url);
const QNetworkRequest request(url);
QNetworkReply *reply = manager.get(request);
}

Lykurg
23rd July 2011, 08:59
Hi,

it is because the get function of QNetworkAccessManager works asynchron. That means that DownloadManager::doDownload returns right after calling get, then ListeXml::downloadd returns and finally it proceed at listeXml.downloadd(qUrl); without Qt had had the chance to start the network request and all objects you create on the stack will be deleted, thus the request will never be sent.

matthieunc
23rd July 2011, 12:45
Right after posting, I kept testing and I found a code that succeeded in downloading the file. The download instruction is in main.cpp, and it's working, so am I missing something about your explaination? here is the main.cpp that got it working (without changing anything else):

main.cpp


#include "mainwindow.h"
#include "listexml.h"

#include <QDebug>
#include <QtGui/QApplication>


int main(int argc, char *argv[])
{
QApplication app(argc, argv);

DownloadManager manager;
manager.doDownload(QString("http://symblr.tumblr.com/api/read/"));

return app.exec();
}


However, I just copied the code from "ListeXml.cpp" to "main.cpp". So... why??
Meanwhile, I'm going to try to code a signal/slot system that ends the doDownload function only when the file is downloaded.

Lykurg
23rd July 2011, 13:12
In main() it succeed because the manager keeps alive. In your further code it gets destroyed right after it was created. Make yourself familiar with the lifetime of objects and with stack/heap allocation.

matthieunc
23rd July 2011, 13:18
I'll follow your advice! Thank you soooo much for your help! :)