tags:

views:

1871

answers:

2

I'm downloading a file using QNetworkAccessManager::get but unlike QHttp::get there's no built-in way to directly write the response to a different QIODevice.

The easiest way would be to do something like this:

QIODevice* device;

QNetworkReply* reply = manager.get(url);
connect(reply, SIGNAL(readyRead()), this, SLOT(newData()));

and then in newData slot:

device->write(reply->readAll());

But I'm not sure if this is the right way, maybe I missed something.

+5  A: 

That looks correct. I would use the lower-level forms of read() and write(), not the QByteArray ones, which do not properly support error handling, but other than that, it looks fine.

Are you having problems with it?

I haven't ran into any problems so far but I'm worried that if I have a big amount of parallel downloads, this whole operation might cause a bottle neck.
Idan K
Unlikely, but possible. You can optimize by using a stack `char buffer[4098]` to avoid the `malloc()s` involved in the `QByteArray` creation. There's also `QVarLengthArray`.
yeah that's what I did with the local char array. thanks for your help.
Idan K
+1  A: 

Better use the finished signal to read all the contents at the end of the download process. An example (remove the event loop and use a new slot to make it asynchronous):

 QNetworkAccessManager manager;
 QEventLoop loop;
 QNetworkReply *reply = manager.get( request );
 QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));

 loop.exec();

 QFile file( "YOUR FILE" );
 file.open(QIODevice::WriteOnly);
 file.write(reply->readAll());

 delete reply;
Das
this can cause some serious memory/performance issues when dealing with large requests
Idan K