Search code examples
qthttpdownloadqnetworkaccessmanager

Qt NetworkAccessManager how to download file via HTTP


today i began a project using Qt, and i am having a little trouble downloading files with NetworkAccessManager. I am very new to Qt and dont quite understand the structure yet, so please bee beginner friendly with your suggestions =)

if it is at all possible, would you be able to post some code to help me out? thanks in advance!


Solution

  • This is an extremely simplified code. All kinds of checks are removed. It is not meant to be copy/pasted into a production system. No logins. No ssl.

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
    this, SLOT(replyFinished(QNetworkReply*)));
    
    QNetworkRequest request;
    request.setUrl(QUrl(source)); // source = url to the file you want to download.
    manager->get(request);
    

    The replyFinished slot:

    replyFinished(QNetworkReply *reply){
     reply->deleteLater();
     QByteArray yourFile = reply->readAll();
    }
    

    Again: Check the docs for details, e.g. error handling. For simplification I assumed, that really the full content of your file is already available when replyFinished is called.