10

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.

Idan K
  • 20,443
  • 10
  • 63
  • 83

2 Answers2

7

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?

Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
  • 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 Jul 30 '09 at 12:45
  • 1
    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`. – Marc Mutz - mmutz Jul 30 '09 at 13:39
  • yeah that's what I did with the local char array. thanks for your help. – Idan K Jul 30 '09 at 15:11
0

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
  • 55
  • 3