util/examples/network/http/httpwindow.cpp
changeset 7 f7bc934e204c
equal deleted inserted replaced
3:41300fa6a67c 7:f7bc934e204c
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
       
     4 ** All rights reserved.
       
     5 ** Contact: Nokia Corporation (qt-info@nokia.com)
       
     6 **
       
     7 ** This file is part of the examples of the Qt Toolkit.
       
     8 **
       
     9 ** $QT_BEGIN_LICENSE:LGPL$
       
    10 ** No Commercial Usage
       
    11 ** This file contains pre-release code and may not be distributed.
       
    12 ** You may use this file in accordance with the terms and conditions
       
    13 ** contained in the Technology Preview License Agreement accompanying
       
    14 ** this package.
       
    15 **
       
    16 ** GNU Lesser General Public License Usage
       
    17 ** Alternatively, this file may be used under the terms of the GNU Lesser
       
    18 ** General Public License version 2.1 as published by the Free Software
       
    19 ** Foundation and appearing in the file LICENSE.LGPL included in the
       
    20 ** packaging of this file.  Please review the following information to
       
    21 ** ensure the GNU Lesser General Public License version 2.1 requirements
       
    22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
       
    23 **
       
    24 ** In addition, as a special exception, Nokia gives you certain additional
       
    25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
       
    26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
       
    27 **
       
    28 ** If you have questions regarding the use of this file, please contact
       
    29 ** Nokia at qt-info@nokia.com.
       
    30 **
       
    31 **
       
    32 **
       
    33 **
       
    34 **
       
    35 **
       
    36 **
       
    37 **
       
    38 ** $QT_END_LICENSE$
       
    39 **
       
    40 ****************************************************************************/
       
    41 
       
    42 #include <QtGui>
       
    43 #include <QtNetwork>
       
    44 
       
    45 #include "httpwindow.h"
       
    46 #include "ui_authenticationdialog.h"
       
    47 
       
    48 HttpWindow::HttpWindow(QWidget *parent)
       
    49     : QDialog(parent)
       
    50 {
       
    51 #ifndef QT_NO_OPENSSL
       
    52     urlLineEdit = new QLineEdit("https://qt.nokia.com/");
       
    53 #else
       
    54     urlLineEdit = new QLineEdit("http://qt.nokia.com/");
       
    55 #endif
       
    56 
       
    57     urlLabel = new QLabel(tr("&URL:"));
       
    58     urlLabel->setBuddy(urlLineEdit);
       
    59     statusLabel = new QLabel(tr("Please enter the URL of a file you want to "
       
    60                                 "download."));
       
    61 
       
    62     downloadButton = new QPushButton(tr("Download"));
       
    63     downloadButton->setDefault(true);
       
    64     quitButton = new QPushButton(tr("Quit"));
       
    65     quitButton->setAutoDefault(false);
       
    66 
       
    67     buttonBox = new QDialogButtonBox;
       
    68     buttonBox->addButton(downloadButton, QDialogButtonBox::ActionRole);
       
    69     buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
       
    70 
       
    71     progressDialog = new QProgressDialog(this);
       
    72 
       
    73     connect(urlLineEdit, SIGNAL(textChanged(QString)),
       
    74             this, SLOT(enableDownloadButton()));
       
    75 
       
    76     connect(&qnam, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
       
    77             this, SLOT(slotAuthenticationRequired(QNetworkReply*,QAuthenticator*)));
       
    78 #ifndef QT_NO_OPENSSL
       
    79     connect(&qnam, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
       
    80             this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
       
    81 #endif
       
    82     connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
       
    83     connect(downloadButton, SIGNAL(clicked()), this, SLOT(downloadFile()));
       
    84     connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
       
    85 
       
    86     QHBoxLayout *topLayout = new QHBoxLayout;
       
    87     topLayout->addWidget(urlLabel);
       
    88     topLayout->addWidget(urlLineEdit);
       
    89 
       
    90     QVBoxLayout *mainLayout = new QVBoxLayout;
       
    91     mainLayout->addLayout(topLayout);
       
    92     mainLayout->addWidget(statusLabel);
       
    93     mainLayout->addWidget(buttonBox);
       
    94     setLayout(mainLayout);
       
    95 
       
    96     setWindowTitle(tr("HTTP"));
       
    97     urlLineEdit->setFocus();
       
    98 }
       
    99 
       
   100 void HttpWindow::startRequest(QUrl url)
       
   101 {
       
   102     reply = qnam.get(QNetworkRequest(url));
       
   103     connect(reply, SIGNAL(finished()),
       
   104             this, SLOT(httpFinished()));
       
   105     connect(reply, SIGNAL(readyRead()),
       
   106             this, SLOT(httpReadyRead()));
       
   107     connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
       
   108             this, SLOT(updateDataReadProgress(qint64,qint64)));
       
   109 }
       
   110 
       
   111 void HttpWindow::downloadFile()
       
   112 {
       
   113     url = urlLineEdit->text();
       
   114 
       
   115     QFileInfo fileInfo(url.path());
       
   116     QString fileName = fileInfo.fileName();
       
   117     if (fileName.isEmpty())
       
   118         fileName = "index.html";
       
   119 
       
   120     if (QFile::exists(fileName)) {
       
   121         if (QMessageBox::question(this, tr("HTTP"), 
       
   122                                   tr("There already exists a file called %1 in "
       
   123                                      "the current directory. Overwrite?").arg(fileName),
       
   124                                   QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
       
   125             == QMessageBox::No)
       
   126             return;
       
   127         QFile::remove(fileName);
       
   128     }
       
   129 
       
   130     file = new QFile(fileName);
       
   131     if (!file->open(QIODevice::WriteOnly)) {
       
   132         QMessageBox::information(this, tr("HTTP"),
       
   133                                  tr("Unable to save the file %1: %2.")
       
   134                                  .arg(fileName).arg(file->errorString()));
       
   135         delete file;
       
   136         file = 0;
       
   137         return;
       
   138     }
       
   139 
       
   140 
       
   141     progressDialog->setWindowTitle(tr("HTTP"));
       
   142     progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
       
   143     downloadButton->setEnabled(false);
       
   144 
       
   145     // schedule the request
       
   146     httpRequestAborted = false;
       
   147     startRequest(url);
       
   148 }
       
   149 
       
   150 void HttpWindow::cancelDownload()
       
   151 {
       
   152     statusLabel->setText(tr("Download canceled."));
       
   153     httpRequestAborted = true;
       
   154     reply->abort();
       
   155     downloadButton->setEnabled(true);
       
   156 }
       
   157 
       
   158 void HttpWindow::httpFinished()
       
   159 {
       
   160     if (httpRequestAborted) {
       
   161         if (file) {
       
   162             file->close();
       
   163             file->remove();
       
   164             delete file;
       
   165             file = 0;
       
   166         }
       
   167         reply->deleteLater();
       
   168         progressDialog->hide();
       
   169         return;
       
   170     }
       
   171 
       
   172     progressDialog->hide();
       
   173     file->flush();
       
   174     file->close();
       
   175 
       
   176 
       
   177     QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
       
   178     if (reply->error()) {
       
   179         file->remove();
       
   180         QMessageBox::information(this, tr("HTTP"),
       
   181                                  tr("Download failed: %1.")
       
   182                                  .arg(reply->errorString()));
       
   183         downloadButton->setEnabled(true);
       
   184     } else if (!redirectionTarget.isNull()) {        
       
   185         QUrl newUrl = url.resolved(redirectionTarget.toUrl());
       
   186         if (QMessageBox::question(this, tr("HTTP"),
       
   187                                   tr("Redirect to %1 ?").arg(newUrl.toString()),
       
   188                                   QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
       
   189             url = newUrl;
       
   190             reply->deleteLater();
       
   191             file->open(QIODevice::WriteOnly);
       
   192             file->resize(0);
       
   193             startRequest(url);
       
   194             return;
       
   195         }
       
   196     } else {
       
   197         QString fileName = QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
       
   198         statusLabel->setText(tr("Downloaded %1 to current directory.").arg(fileName));
       
   199         downloadButton->setEnabled(true);
       
   200     }
       
   201 
       
   202     reply->deleteLater();
       
   203     reply = 0;
       
   204     delete file;
       
   205     file = 0;
       
   206 }
       
   207 
       
   208 void HttpWindow::httpReadyRead()
       
   209 {
       
   210     // this slot gets called everytime the QNetworkReply has new data.
       
   211     // We read all of its new data and write it into the file.
       
   212     // That way we use less RAM than when reading it at the finished()
       
   213     // signal of the QNetworkReply
       
   214     if (file)
       
   215         file->write(reply->readAll());
       
   216 }
       
   217 
       
   218 void HttpWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
       
   219 {
       
   220     if (httpRequestAborted)
       
   221         return;
       
   222 
       
   223     progressDialog->setMaximum(totalBytes);
       
   224     progressDialog->setValue(bytesRead);
       
   225 }
       
   226 
       
   227 void HttpWindow::enableDownloadButton()
       
   228 {
       
   229     downloadButton->setEnabled(!urlLineEdit->text().isEmpty());
       
   230 }
       
   231 
       
   232 void HttpWindow::slotAuthenticationRequired(QNetworkReply*,QAuthenticator *authenticator)
       
   233 {
       
   234     QDialog dlg;
       
   235     Ui::Dialog ui;
       
   236     ui.setupUi(&dlg);
       
   237     dlg.adjustSize();
       
   238     ui.siteDescription->setText(tr("%1 at %2").arg(authenticator->realm()).arg(url.host()));
       
   239 
       
   240     // Did the URL have information? Fill the UI
       
   241     // This is only relevant if the URL-supplied credentials were wrong
       
   242     ui.userEdit->setText(url.userName());
       
   243     ui.passwordEdit->setText(url.password());
       
   244 
       
   245     if (dlg.exec() == QDialog::Accepted) {
       
   246         authenticator->setUser(ui.userEdit->text());
       
   247         authenticator->setPassword(ui.passwordEdit->text());
       
   248     }
       
   249 }
       
   250 
       
   251 #ifndef QT_NO_OPENSSL
       
   252 void HttpWindow::sslErrors(QNetworkReply*,const QList<QSslError> &errors)
       
   253 {
       
   254     QString errorString;
       
   255     foreach (const QSslError &error, errors) {
       
   256         if (!errorString.isEmpty())
       
   257             errorString += ", ";
       
   258         errorString += error.errorString();
       
   259     }
       
   260     
       
   261     if (QMessageBox::warning(this, tr("HTTP"),
       
   262                              tr("One or more SSL errors has occurred: %1").arg(errorString),
       
   263                              QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) {
       
   264         reply->ignoreSslErrors();
       
   265     }
       
   266 }
       
   267 #endif