examples/network/http/httpwindow.cpp
changeset 0 1918ee327afb
child 3 41300fa6a67c
equal deleted inserted replaced
-1:000000000000 0:1918ee327afb
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2009 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://");
       
    53 #else
       
    54     urlLineEdit = new QLineEdit("http://");
       
    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     http = new QHttp(this);
       
    74 
       
    75     connect(urlLineEdit, SIGNAL(textChanged(const QString &)),
       
    76             this, SLOT(enableDownloadButton()));
       
    77     connect(http, SIGNAL(requestFinished(int, bool)),
       
    78             this, SLOT(httpRequestFinished(int, bool)));
       
    79     connect(http, SIGNAL(dataReadProgress(int, int)),
       
    80             this, SLOT(updateDataReadProgress(int, int)));
       
    81     connect(http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)),
       
    82             this, SLOT(readResponseHeader(const QHttpResponseHeader &)));
       
    83     connect(http, SIGNAL(authenticationRequired(const QString &, quint16, QAuthenticator *)),
       
    84             this, SLOT(slotAuthenticationRequired(const QString &, quint16, QAuthenticator *)));
       
    85 #ifndef QT_NO_OPENSSL
       
    86     connect(http, SIGNAL(sslErrors(const QList<QSslError> &)),
       
    87             this, SLOT(sslErrors(const QList<QSslError> &)));
       
    88 #endif
       
    89     connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
       
    90     connect(downloadButton, SIGNAL(clicked()), this, SLOT(downloadFile()));
       
    91     connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
       
    92 
       
    93     QHBoxLayout *topLayout = new QHBoxLayout;
       
    94     topLayout->addWidget(urlLabel);
       
    95     topLayout->addWidget(urlLineEdit);
       
    96 
       
    97     QVBoxLayout *mainLayout = new QVBoxLayout;
       
    98     mainLayout->addLayout(topLayout);
       
    99     mainLayout->addWidget(statusLabel);
       
   100     mainLayout->addWidget(buttonBox);
       
   101     setLayout(mainLayout);
       
   102 
       
   103     setWindowTitle(tr("HTTP"));
       
   104     urlLineEdit->setFocus();
       
   105 }
       
   106 
       
   107 void HttpWindow::downloadFile()
       
   108 {
       
   109     QUrl url(urlLineEdit->text());
       
   110     QFileInfo fileInfo(url.path());
       
   111     QString fileName = fileInfo.fileName();
       
   112     if (fileName.isEmpty())
       
   113         fileName = "index.html";
       
   114 
       
   115     if (QFile::exists(fileName)) {
       
   116         if (QMessageBox::question(this, tr("HTTP"), 
       
   117                                   tr("There already exists a file called %1 in "
       
   118                                      "the current directory. Overwrite?").arg(fileName),
       
   119                                   QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
       
   120             == QMessageBox::No)
       
   121             return;
       
   122         QFile::remove(fileName);
       
   123     }
       
   124 
       
   125     file = new QFile(fileName);
       
   126     if (!file->open(QIODevice::WriteOnly)) {
       
   127         QMessageBox::information(this, tr("HTTP"),
       
   128                                  tr("Unable to save the file %1: %2.")
       
   129                                  .arg(fileName).arg(file->errorString()));
       
   130         delete file;
       
   131         file = 0;
       
   132         return;
       
   133     }
       
   134 
       
   135     QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
       
   136     http->setHost(url.host(), mode, url.port() == -1 ? 0 : url.port());
       
   137     
       
   138     if (!url.userName().isEmpty())
       
   139         http->setUser(url.userName(), url.password());
       
   140 
       
   141     httpRequestAborted = false;
       
   142     QByteArray path = QUrl::toPercentEncoding(url.path(), "!$&'()*+,;=:@/");
       
   143     if (path.isEmpty())
       
   144         path = "/";
       
   145     httpGetId = http->get(path, file);
       
   146 
       
   147     progressDialog->setWindowTitle(tr("HTTP"));
       
   148     progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
       
   149     downloadButton->setEnabled(false);
       
   150 }
       
   151 
       
   152 void HttpWindow::cancelDownload()
       
   153 {
       
   154     statusLabel->setText(tr("Download canceled."));
       
   155     httpRequestAborted = true;
       
   156     http->abort();
       
   157     downloadButton->setEnabled(true);
       
   158 }
       
   159 
       
   160 void HttpWindow::httpRequestFinished(int requestId, bool error)
       
   161 {
       
   162     if (requestId != httpGetId)
       
   163         return;
       
   164     if (httpRequestAborted) {
       
   165         if (file) {
       
   166             file->close();
       
   167             file->remove();
       
   168             delete file;
       
   169             file = 0;
       
   170         }
       
   171 
       
   172         progressDialog->hide();
       
   173         return;
       
   174     }
       
   175 
       
   176     if (requestId != httpGetId)
       
   177         return;
       
   178 
       
   179     progressDialog->hide();
       
   180     file->close();
       
   181 
       
   182     if (error) {
       
   183         file->remove();
       
   184         QMessageBox::information(this, tr("HTTP"),
       
   185                                  tr("Download failed: %1.")
       
   186                                  .arg(http->errorString()));
       
   187     } else {
       
   188         QString fileName = QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
       
   189         statusLabel->setText(tr("Downloaded %1 to current directory.").arg(fileName));
       
   190     }
       
   191 
       
   192     downloadButton->setEnabled(true);
       
   193     delete file;
       
   194     file = 0;
       
   195 }
       
   196 
       
   197 void HttpWindow::readResponseHeader(const QHttpResponseHeader &responseHeader)
       
   198 {
       
   199     switch (responseHeader.statusCode()) {
       
   200     case 200:                   // Ok
       
   201     case 301:                   // Moved Permanently
       
   202     case 302:                   // Found
       
   203     case 303:                   // See Other
       
   204     case 307:                   // Temporary Redirect
       
   205         // these are not error conditions
       
   206         break;
       
   207 
       
   208     default:
       
   209         QMessageBox::information(this, tr("HTTP"),
       
   210                                  tr("Download failed: %1.")
       
   211                                  .arg(responseHeader.reasonPhrase()));
       
   212         httpRequestAborted = true;
       
   213         progressDialog->hide();
       
   214         http->abort();
       
   215     }
       
   216 }
       
   217 
       
   218 void HttpWindow::updateDataReadProgress(int bytesRead, int 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(const QString &hostName, quint16, 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(hostName));
       
   239     
       
   240     if (dlg.exec() == QDialog::Accepted) {
       
   241         authenticator->setUser(ui.userEdit->text());
       
   242         authenticator->setPassword(ui.passwordEdit->text());
       
   243     }
       
   244 }
       
   245 
       
   246 #ifndef QT_NO_OPENSSL
       
   247 void HttpWindow::sslErrors(const QList<QSslError> &errors)
       
   248 {
       
   249     QString errorString;
       
   250     foreach (const QSslError &error, errors) {
       
   251         if (!errorString.isEmpty())
       
   252             errorString += ", ";
       
   253         errorString += error.errorString();
       
   254     }
       
   255     
       
   256     if (QMessageBox::warning(this, tr("HTTP Example"),
       
   257                              tr("One or more SSL errors has occurred: %1").arg(errorString),
       
   258                              QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) {
       
   259         http->ignoreSslErrors();
       
   260     }
       
   261 }
       
   262 #endif