Qt5 - 从网址

时间:2016-07-07 13:07:24

标签: qt download httprequest qt5

我正在下载" .apk"带有Get方法的Url文件。 该文件从服务器成功下载到我的磁盘上。 我实际上想在我的程序中添加一个进度条。问题是:我可以显示bytesReceived,但是我无法显示我正在下载的文件的totalBytes(ContentLenth)。我怎么能从服务器上得到它。

以下是我在下载时在qDebug上获得的内容:

    3498 of -1
    799062 of -1
    1923737 of -1
    3037550 of -1
    3200231 of 3200231

这是我的代码:

void DownloadApk::LaunchDownload()
{
    QNetworkProxy proxy;
    proxy.setType(QNetworkProxy::HttpProxy);
    proxy.setHostName("proxy");
    proxy.setPort(8080);
    QNetworkProxy::setApplicationProxy(proxy);


    QUrl url("I put my Url here");
    QNetworkRequest request(url);


  _file = new QFile("C:/Users/Desktop/testdownload/downloadedFile.apk");
  _file->open(QIODevice::WriteOnly);


  QNetworkAccessManager *_manager= new QNetworkAccessManager;
  _reply = _manager->get(request);// Manager is my QNetworkAccessManager
  _file->write(_reply->readAll());
  connect(_reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(error(QNetworkReply::NetworkError)));
  connect(_reply, SIGNAL(downloadProgress(qint64, qint64)),
            this, SLOT(updateProgress(qint64, qint64)));
  connect(_reply, SIGNAL(finished()),
            this, SLOT(finished()));
}


void DownloadApk::error(QNetworkReply::NetworkError err)
{qDebug() << err;
    // Manage error here.
    _reply->deleteLater();
}
void DownloadApk::updateProgress(qint64 read, qint64 total)
{   
    qDebug() << read <<"of"<<total ;
    QByteArray b = _reply->readAll();
    QDataStream out(_file);
    out << b;
}

void DownloadApk::finished()
{
     QMessageBox::information(this, tr("Complete"), tr("Successfully Downloaded"));
    // Done
    _reply->deleteLater();
    _file->close();
    // probably delete the file object too
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。实际上这不是QT问题。此Qt代码正常工作。 问题来自服务器,该服务器没有在回复的标题上发送ContentLenth。