示例#1
0
void HttpHandler::postFinished(QNetworkReply* reply){
    QVariant possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    /* We'll deduct if the redirection is valid in the redirectUrl function */
    qDebug() << "Redirect: " <<  possibleRedirectUrl.toUrl().toString();

    qDebug() << "File sent";
    QByteArray response = reply->readAll();
        printf("response: %s\n", response.data() );
        printf("reply error %d\n", reply->error() );
    reply->deleteLater();
    ba.clear();

}
bool QNetworkAccessCacheBackend::sendCacheContents()
{
    setCachingEnabled(false);
    QAbstractNetworkCache *nc = networkCache();
    if (!nc)
        return false;

    QNetworkCacheMetaData item = nc->metaData(url());
    if (!item.isValid())
        return false;

    QNetworkCacheMetaData::AttributesMap attributes = item.attributes();
    setAttribute(QNetworkRequest::HttpStatusCodeAttribute, attributes.value(QNetworkRequest::HttpStatusCodeAttribute));
    setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, attributes.value(QNetworkRequest::HttpReasonPhraseAttribute));

    // set the raw headers
    QNetworkCacheMetaData::RawHeaderList rawHeaders = item.rawHeaders();
    QNetworkCacheMetaData::RawHeaderList::ConstIterator it = rawHeaders.constBegin(),
                                                       end = rawHeaders.constEnd();
    for ( ; it != end; ++it) {
        if (it->first.toLower() == "cache-control" &&
            it->second.toLower().contains("must-revalidate")) {
            return false;
        }
        setRawHeader(it->first, it->second);
    }

    // handle a possible redirect
    QVariant redirectionTarget = attributes.value(QNetworkRequest::RedirectionTargetAttribute);
    if (redirectionTarget.isValid()) {
        setAttribute(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
        redirectionRequested(redirectionTarget.toUrl());
    }

    // signal we're open
    metaDataChanged();

    if (operation() == QNetworkAccessManager::GetOperation) {
        QIODevice *contents = nc->data(url());
        if (!contents)
            return false;
        contents->setParent(this);
        writeDownstreamData(contents);
    }

#if defined(QNETWORKACCESSCACHEBACKEND_DEBUG)
    qDebug() << "Successfully sent cache:" << url();
#endif
    return true;
}
示例#3
0
void HttpWindow::httpFinished()
{
    if (httpRequestAborted) {
        if (file) {
            file->close();
            file->remove();
            delete file;
            file = 0;
        }
        reply->deleteLater();
        progressDialog->hide();
        return;
    }

    progressDialog->hide();
    file->flush();
    file->close();


    QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if (reply->error()) {
        file->remove();
        QMessageBox::information(this, tr("HTTP"),
                                 tr("Download failed: %1.")
                                 .arg(reply->errorString()));
        downloadButton->setEnabled(true);
    } else if (!redirectionTarget.isNull()) {        
        QUrl newUrl = url.resolved(redirectionTarget.toUrl());
        if (QMessageBox::question(this, tr("HTTP"),
                                  tr("Redirect to %1 ?").arg(newUrl.toString()),
                                  QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
            url = newUrl;
            reply->deleteLater();
            file->open(QIODevice::WriteOnly);
            file->resize(0);
            startRequest(url);
            return;
        }
    } else {
        QString fileName = QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
        statusLabel->setText(tr("Downloaded %1 to current directory.").arg(fileName));
        downloadButton->setEnabled(true);
    }

    reply->deleteLater();
    reply = 0;
    delete file;
    file = 0;
}
示例#4
0
void StartMainPage::slotListViewActivated(const QModelIndex& index)
{
    if (!index.isValid()) {
        return;
    }
    QVariant data = index.data(KFilePlacesModel::UrlRole);
    KUrl url = data.toUrl();

    // Prevent dir lister error
    if (!url.isValid()) {
        kError() << "Tried to open an invalid url";
        return;
    }
    emit urlSelected(url);
}
示例#5
0
void DownloadItem::metaDataChanged()
{
    QVariant locationHeader = m_reply->header(QNetworkRequest::LocationHeader);
    if (locationHeader.isValid()) {
        m_url = locationHeader.toUrl();
        m_reply->deleteLater();
        m_reply = BrowserApplication::networkAccessManager()->get(QNetworkRequest(m_url));
        init();
        return;
    }

#ifdef DOWNLOADMANAGER_DEBUG
    qDebug() << "DownloadItem::" << __FUNCTION__ << "not handled.";
#endif
}
示例#6
0
int Updater::checkManifest()
{
    QUrl baseUrl(MANIFEST_URL);
    QNetworkAccessManager manager;
    QNetworkRequest request = getNetworkRequest(baseUrl);
    QNetworkReply *rep = manager.get(request);

    while(rep->error() == QNetworkReply::NoError && !rep->isFinished())
        QCoreApplication::processEvents();

    while(true)
    {
        while(!rep->isFinished())
            QCoreApplication::processEvents();

        if(rep->error() != QNetworkReply::NoError)
            return RES_CHECK_FAILED;

        QVariant redirect = rep->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if(redirect.type() != QVariant::Url)
            break;

        // redirect
        baseUrl = baseUrl.resolved(redirect.toUrl());
        request = getNetworkRequest(baseUrl);
        rep = manager.get(request);
    }

    if(rep->isFinished() && rep->size() != 0)
    {
        QString s;
        QString ver(VERSION);
        while(!rep->atEnd())
        {
            s = rep->readLine();

            QStringList parts = s.split(' ', QString::SkipEmptyParts);
            if(parts.size() < 3 || !ver.contains(parts[0]))
                continue;

            if(REVISION < parts[1].toInt())
                return RES_UPDATE_AVAILABLE;
            else
                return RES_NO_UPDATE;
        }
    }
    return RES_NO_UPDATE;
}
 bool DownloadManager::hasRedirect( QNetworkReply *reply )
 {
     if( reply->error() == QNetworkReply::NoError ){
         QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
         if( !redirect.isNull() ){
             QUrl originalUrl = reply->request().url();
             QString newUrl = originalUrl.resolved( redirect.toUrl() ).toString();
             stopDownload( originalUrl.toString() );
             startDownload( newUrl );
             return true;
         } else {
             return false;
         }
     }
     return false;
 }
void KDUpdater::HttpDownloader::httpReqFinished()
{
    const QVariant redirect = d->http == 0 ? QVariant() : d->http->attribute( QNetworkRequest::RedirectionTargetAttribute );
    const QUrl redirectUrl = redirect.toUrl();

    if ( followRedirects() && redirectUrl.isValid() )
    {
        if ( d->redirectList.contains( redirectUrl.toString() ) )
        {
            // redirected in an infinte loop or no new url thats an error
            d->destination->remove();
            setDownloadAborted( tr( "Not Found" ) );
        }
        else
        {
            d->redirectList.push_back( redirectUrl.toString() );
            // clean the previous download
            d->http->deleteLater();
            d->http = 0;
            d->destination->close();
            d->destination->deleteLater();
            d->destination = 0;

            d->http = d->manager.get( QNetworkRequest( redirectUrl ) );

            connect( d->http, SIGNAL(readyRead()), this, SLOT(httpReadyRead()) );
            connect( d->http, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(httpReadProgress(qint64,qint64)) );
            connect( d->http, SIGNAL(finished()), this, SLOT(httpReqFinished()) );
            connect( d->http, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(httpError(QNetworkReply::NetworkError)) );

            // Begin the download
            d->destination = new QTemporaryFile(this);
            d->destination->open(); //PENDING handle error
        }
    }
    else
    {
        if( d->http == 0 )
            return;
        httpReadyRead();
        d->destination->flush();
        setDownloadCompleted( d->destination->fileName() );
        d->http->deleteLater();
        d->http = 0;
    }
}
示例#9
0
QString NativeSeparatorsDelegate::displayText(const QVariant& value, const QLocale&) const {
  const QString string_value = value.toString();

  QUrl url;
  if (value.type() == QVariant::Url) {
    url = value.toUrl();
  } else if (string_value.contains("://")) {
    url = QUrl::fromEncoded(string_value.toAscii());
  } else {
    return QDir::toNativeSeparators(string_value);
  }

  if (url.scheme() == "file") {
    return QDir::toNativeSeparators(url.toLocalFile());
  }
  return string_value;
}
示例#10
0
QVariant ObjectNodeInstance::fixResourcePaths(const QVariant &value)
{
    if (value.type() == QVariant::Url)
    {
        const QUrl url = value.toUrl();
        if (url.scheme() == QLatin1String("qrc")) {
            const QString path = QLatin1String("qrc:") +  url.path();
            QString qrcSearchPath = qgetenv("QMLDESIGNER_RC_PATHS");
            if (!qrcSearchPath.isEmpty()) {
                const QStringList searchPaths = qrcSearchPath.split(QLatin1Char(';'));
                foreach (const QString &qrcPath, searchPaths) {
                    const QStringList qrcDefintion = qrcPath.split(QLatin1Char('='));
                    if (qrcDefintion.count() == 2) {
                        QString fixedPath = path;
                        fixedPath.replace(QLatin1String("qrc:") + qrcDefintion.first(), qrcDefintion.last() + QLatin1Char('/'));
                        if (QFileInfo(fixedPath).exists()) {
                            fixedPath.replace(QLatin1String("//"), QLatin1String("/"));
                            fixedPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
                            return QUrl(fixedPath);
                        }
                    }
                }
            }
        }
    }
    if (value.type() == QVariant::String) {
        const QString str = value.toString();
        if (str.contains(QLatin1String("qrc:"))) {
            QString qrcSearchPath = qgetenv("QMLDESIGNER_RC_PATHS");
            if (!qrcSearchPath.isEmpty()) {
                const QStringList searchPaths = qrcSearchPath.split(QLatin1Char(';'));
                foreach (const QString &qrcPath, searchPaths) {
                    const QStringList qrcDefintion = qrcPath.split(QLatin1Char('='));
                    if (qrcDefintion.count() == 2) {
                        QString fixedPath = str;
                        fixedPath.replace(QLatin1String("qrc:") + qrcDefintion.first(), qrcDefintion.last() + QLatin1Char('/'));
                        if (QFileInfo(fixedPath).exists()) {
                            fixedPath.replace(QLatin1String("//"), QLatin1String("/"));
                            fixedPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
                            return fixedPath;
                        }
                    }
                }
            }
        }
    }
示例#11
0
/*!
    Returns an icon URL according to the given \a size.

    If no manager has been assigned to the icon, and the parameters do not contain the QPlaceIcon::SingleUrl key, a default constructed QUrl
    is returned.
*/
QUrl QPlaceIcon::url(const QSize &size) const
{
    if (d->parameters.contains(QPlaceIcon::SingleUrl)) {
        QVariant value = d->parameters.value(QPlaceIcon::SingleUrl);
        if (value.type() == QVariant::Url)
            return value.toUrl();
        else if (value.type() == QVariant::String)
            return QUrl::fromUserInput(value.toString());

        return QUrl();
    }

    if (!d->manager)
        return QUrl();

    return d->manager->d->constructIconUrl(*this, size);
}
示例#12
0
Song SoundCloudService::ExtractSong(const QVariantMap& result_song) {
  Song song;
  if (!result_song.isEmpty() && result_song["streamable"].toBool()) {
    QUrl stream_url = result_song["stream_url"].toUrl();
    stream_url.addQueryItem("client_id", kApiClientId);
    song.set_url(stream_url);

    QString username = result_song["user"].toMap()["username"].toString();
    // We don't have a real artist name, but username is the most similar thing
    // we have
    song.set_artist(username);

    QString title = result_song["title"].toString();
    song.set_title(title);

    QString genre = result_song["genre"].toString();
    song.set_genre(genre);

    float bpm = result_song["bpm"].toFloat();
    song.set_bpm(bpm);

    QVariant cover = result_song["artwork_url"];
    if (cover.isValid()) {
      // SoundCloud covers URL are https, but our cover loader doesn't seem to
      // deal well with https URL. Anyway, we don't need a secure connection to
      // get a cover image.
      QUrl cover_url = cover.toUrl();
      cover_url.setScheme("http");
      song.set_art_automatic(cover_url.toEncoded());
    }

    int playcount = result_song["playback_count"].toInt();
    song.set_playcount(playcount);

    int year = result_song["release_year"].toInt();
    song.set_year(year);

    QVariant q_duration = result_song["duration"];
    quint64 duration = q_duration.toULongLong() * kNsecPerMsec;
    song.set_length_nanosec(duration);

    song.set_valid(true);
  }
  return song;
}
void ManageDefinitionsDialog::downloadDefinitions()
{
    if (Manager::instance()->isDownloadingDefinitions()) {
        QMessageBox::information(
            this,
            tr("Download Information"),
            tr("There is already one download in progress. Please wait until it is finished."));
        return;
    }

    QList<QUrl> urls;
    foreach (const QModelIndex &index, ui.definitionsTable->selectionModel()->selectedRows()) {
        const QVariant url = ui.definitionsTable->item(index.row(), 0)->data(Qt::UserRole);
        urls.append(url.toUrl());
    }
    Manager::instance()->downloadDefinitions(urls, m_path);
    accept();
}
示例#14
0
void DefinitionUpdater::checkReply() {
  // check for server side redirection
  QVariant redir = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
  if (!redir.isNull()) {
    reply->deleteLater();
    // start update again with redirected URL
    url = redir.toUrl();
    update();
    return;
  }
  // final URL found -> get data
  reply->deleteLater();
  reply = qnam.get(QNetworkRequest(url));
  connect(reply, SIGNAL(finished()),
          this, SLOT(finishUpdate()));
  connect(reply, SIGNAL(readyRead()),
          this, SLOT(checkVersion()));
}
示例#15
0
void QgsFileDownloader::onFinished()
{
  // when canceled
  if ( ! mErrors.isEmpty() || mDownloadCanceled )
  {
    mFile.close();
    mFile.remove();
    if ( mGuiNotificationsEnabled )
      mProgressDialog->hide();
  }
  else
  {
    // download finished normally
    if ( mGuiNotificationsEnabled )
      mProgressDialog->hide();
    mFile.flush();
    mFile.close();

    // get redirection url
    QVariant redirectionTarget = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
    if ( mReply->error() )
    {
      mFile.remove();
      error( tr( "Download failed: %1" ).arg( mReply->errorString() ) );
    }
    else if ( !redirectionTarget.isNull() )
    {
      QUrl newUrl = mUrl.resolved( redirectionTarget.toUrl() );
      mUrl = newUrl;
      mReply->deleteLater();
      mFile.open( QIODevice::WriteOnly );
      mFile.resize( 0 );
      mFile.close();
      startDownload();
      return;
    }
    else
    {
      emit downloadCompleted();
    }
  }
  emit downloadExited();
  this->deleteLater();
}
示例#16
0
/*!
    \reimp

    If the role is the UrlRole then handle otherwise just pass to QStandardItemModel
*/
bool QUrlModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (value.type() == QVariant::Url) {
        QUrl url = value.toUrl();
        QModelIndex dirIndex = fileSystemModel->index(url.toLocalFile());
        //On windows the popup display the "C:\", convert to nativeSeparators
        if (showFullPath)
            QStandardItemModel::setData(index, QDir::toNativeSeparators(fileSystemModel->data(dirIndex, QFileSystemModel::FilePathRole).toString()));
        else {
            QStandardItemModel::setData(index, QDir::toNativeSeparators(fileSystemModel->data(dirIndex, QFileSystemModel::FilePathRole).toString()), Qt::ToolTipRole);
            QStandardItemModel::setData(index, fileSystemModel->data(dirIndex).toString());
        }
        QStandardItemModel::setData(index, fileSystemModel->data(dirIndex, Qt::DecorationRole),
                                               Qt::DecorationRole);
        QStandardItemModel::setData(index, url, UrlRole);
        return true;
    }
    return QStandardItemModel::setData(index, value, role);
}
示例#17
0
/*!
    \internal
    Internally used slot which is invoked when a download is finished.
    This handles redirection of URLs internally, as well as error checking.

    A successful download will emit the downloadComplete() signal which
    the user is responsible for handling in their own application.

    \sa downloadComplete()
*/
void QDownloadManager::netReplyDone()
{
    //Ensure sanity of the sender
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    //Q_ASSERT(reply);
    if (!reply) {
        qWarning("DownloadManager's signal sender was not a QNetworkReply.");
        return;
    }

    if (reply->error() != QNetworkReply::NoError) {
        qWarning() << "Error in network reply: " << reply->url() << "(" << reply->errorString() << ")";
        reply->deleteLater();
        emit downloadComplete(NULL);
        return;
    }

    //In the case of a reply which is a redirect
    QVariant redirection = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if (redirection.isValid()) {
        QUrl url = redirection.toUrl();
        //Check if we have a relative URL
        if (url.isRelative()) {
            url.setScheme(reply->url().scheme());
            url.setHost(reply->url().host());
        }

        //Reissue redirected request.
        QNetworkRequest request(url);
        QNetworkReply * netReply = m_netAccessMgr->get(request);
        connect(netReply, SIGNAL(finished()), SLOT(netReplyDone()));
        reply->deleteLater();
        return;
    }

    //In the case of just data being returned
    //qDebug() << "ContentType:" << reply->header(QNetworkRequest::ContentTypeHeader).toString();
    QByteArray *assetData = new QByteArray();
    *assetData = reply->readAll();
    reply->deleteLater();

    emit downloadComplete(assetData);
}
示例#18
0
void HttpContext::headerReceived() {
  // check to see if it is the request we made
  if (reply != qobject_cast<QNetworkReply *>(sender()))
    return;

  processed = true;

  if ((status = isHtml = (reply->error() == QNetworkReply::NoError))) {
    QVariant value = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if (value.canConvert<int>()) {
      code = value.toInt();

      if (code > 399) /* error codes */
        isHtml = false;
      else if ((code > 299) && (code < 305 || code == 307)) {
        /* redirection codes */
        redirected = true;
        QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

        if (!redirectionTarget.isNull())
          data = QStringToTlpString(redirectionTarget.toUrl().toString());
        else
          data = "";

        reply->close();
        reply->deleteLater();
        reply = nullptr;
      }

      return;
    }

    /* normal codes */
    value = reply->header(QNetworkRequest::ContentTypeHeader);
    status = isHtml =
        (value.canConvert<QString>() && value.toString().contains(QString("text/html")));
    reply->close();
    reply->deleteLater();
    reply = nullptr;
  }
}
示例#19
0
void StartMainPage::showRecentFoldersViewContextMenu(const QPoint& pos)
{
    QAbstractItemView* view = qobject_cast<QAbstractItemView*>(sender());
    KUrl url;
    QModelIndex index = view->indexAt(pos);
    if (index.isValid()) {
        QVariant data = index.data(KFilePlacesModel::UrlRole);
        url = data.toUrl();
    }

    // Create menu
    QMenu menu(this);
    bool fromRecentUrls = view == d->mRecentUrlsView;
    QAction* addToPlacesAction = fromRecentUrls ? 0 : menu.addAction(KIcon("bookmark-new"), i18n("Add to Places"));
    QAction* removeAction = menu.addAction(KIcon("edit-delete"), fromRecentUrls ? i18n("Forget this URL") : i18n("Forget this Folder"));
    menu.addSeparator();
    QAction* clearAction = menu.addAction(KIcon("edit-delete-all"), i18n("Forget All"));

    if (!index.isValid()) {
        if (addToPlacesAction) {
            addToPlacesAction->setEnabled(false);
        }
        removeAction->setEnabled(false);
    }

    // Handle menu
    QAction* action = menu.exec(view->mapToGlobal(pos));
    if (!action) {
        return;
    }
    if (action == addToPlacesAction) {
        QString text = url.fileName();
        if (text.isEmpty()) {
            text = url.pathOrUrl();
        }
        d->mBookmarksModel->addPlace(text, url);
    } else if (action == removeAction) {
        view->model()->removeRow(index.row());
    } else if (action == clearAction) {
        view->model()->removeRows(0, view->model()->rowCount());
    }
}
示例#20
0
void RSSEditPopup::slotCheckRedirect(QNetworkReply* reply)
{
    QVariant possibleRedirectUrl =
         reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    QUrl urlRedirectedTo = redirectUrl(possibleRedirectUrl.toUrl(),
                                       urlRedirectedTo);

    if(!urlRedirectedTo.isEmpty())
    {
        m_urlEdit->SetText(urlRedirectedTo.toString());
        m_manager->get(QNetworkRequest(urlRedirectedTo));
    }
    else
    {
//        urlRedirectedTo.clear();
        slotSave(reply);
    }
    reply->deleteLater();
}
示例#21
0
void KDUpdater::HttpDownloader::httpReqFinished()
{
    const QVariant redirect = d->http == 0 ? QVariant()
        : d->http->attribute(QNetworkRequest::RedirectionTargetAttribute);

    const QUrl redirectUrl = redirect.toUrl();
    if (followRedirects() && redirectUrl.isValid()) {
        d->shutDown();  // clean the previous download
        startDownload(redirectUrl);
    } else {
        if (d->http == 0)
            return;

        httpReadyRead();
        d->destination->flush();
        setDownloadCompleted();
        d->http->deleteLater();
        d->http = 0;
    }
}
void ObjectNodeInstance::doResetProperty(const QString &propertyName)
{
    m_modelAbstractPropertyHash.remove(propertyName);

    QDeclarativeProperty property(object(), propertyName, context());

    if (!property.isValid())
        return;

    QVariant oldValue = property.read();
    if (oldValue.type() == QVariant::Url) {
        QUrl url = oldValue.toUrl();
        QString path = url.toLocalFile();
        if (QFileInfo(path).exists() && nodeInstanceView())
            nodeInstanceView()->removeFilePropertyFromFileSystemWatcher(object(), propertyName, path);
    }


    QDeclarativeAbstractBinding *binding = QDeclarativePropertyPrivate::binding(property);
    if (binding) {
        binding->setEnabled(false, 0);
        binding->destroy();
    }

    if (property.isResettable()) {
        property.reset();
    } else if (property.propertyTypeCategory() == QDeclarativeProperty::List) {
        QDeclarativeListReference list = qvariant_cast<QDeclarativeListReference>(property.read());

        if (!hasFullImplementedListInterface(list)) {
            qWarning() << "Property list interface not fully implemented for Class " << property.property().typeName() << " in property " << property.name() << "!";
            return;
        }

        list.clear();
    } else if (property.isWritable()) {
        if (property.read() == resetValue(propertyName))
            return;
        property.write(resetValue(propertyName));
    }
}
示例#23
0
void DownloadHandler::processFinishedDownload()
{
    QString url = m_reply->url().toString();
    qDebug("Download finished: %s", qPrintable(url));
    // Check if the request was successful
    if (m_reply->error() != QNetworkReply::NoError) {
        // Failure
        qDebug("Download failure (%s), reason: %s", qPrintable(url), qPrintable(errorCodeToString(m_reply->error())));
        emit downloadFailed(m_url, errorCodeToString(m_reply->error()));
        this->deleteLater();
    }
    else {
        // Check if the server ask us to redirect somewhere else
        const QVariant redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if (redirection.isValid()) {
            // We should redirect
            handleRedirection(redirection.toUrl());
        }
        else {
            // Success
            QByteArray replyData = m_reply->readAll();
            if (m_reply->rawHeader("Content-Encoding") == "gzip") {
                // uncompress gzip reply
                Utils::Gzip::uncompress(replyData, replyData);
            }

            if (m_saveToFile) {
                QString filePath;
                if (saveToFile(replyData, filePath))
                    emit downloadFinished(m_url, filePath);
                else
                    emit downloadFailed(m_url, tr("I/O Error"));
                }
            else {
                emit downloadFinished(m_url, replyData);
            }

            this->deleteLater();
        }
    }
}
示例#24
0
void lmcWebNetwork::replyFinished(QNetworkReply *reply)
{
	if(reply->error() != QNetworkReply::NoError)
		return;

	// check if there was an HTTP redirection
	QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
	if(!redirect.isNull()) {
		// send a new request to the redirected url
		sendMessage(redirect.toUrl());
	} else {
		// no redirection, get the data from the reply
		QByteArray data = reply->readAll();
		QString szMessage = QString(data.constData());
		emit messageReceived(&szMessage);
		reply->close();
	}

	reply->deleteLater();
	active = false;
}
示例#25
0
// Shutdown the application server
bool shutdownServer(QUrl url)
{
    QNetworkAccessManager manager;
    QEventLoop loop;
    QNetworkReply *reply;
    QVariant redirectUrl;

    url.setPath("/misc/shutdown");

    do
    {
        reply = manager.get(QNetworkRequest(url));

        QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        url = redirectUrl.toUrl();

        if (!redirectUrl.isNull())
            delete reply;

    } while (!redirectUrl.isNull());

    if (reply->error() != QNetworkReply::NoError)
    {
        return false;
    }

    QString response = reply->readAll();

    if (response != "SHUTDOWN")
    {
        qDebug() << "Failed to connect, server response: " << response;
        return false;
    }

    return true;
}
示例#26
0
void ArrivalsLogic::onStationsDownloaded() {
    int httpCode = reply_stations->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    qDebug() << "HTTP response" << httpCode;

    if (reply_stations->error() != QNetworkReply::NoError) {
        qDebug() << "HTTP returned error:" << httpCode;
    }

    if (httpCode > 300 && httpCode < 400) {
        QVariant redirectUrl = reply_stations->attribute(QNetworkRequest::RedirectionTargetAttribute);
        reply_stations->deleteLater();
        QUrl url = reply_stations->url().resolved(redirectUrl.toUrl());
        qDebug() << "redirecting to" << url;
        reply_stations = networkMngr->get(QNetworkRequest(url));

        connect(reply_stations,SIGNAL(finished()),this, SLOT(onStationsDownloaded()) );
    }
    else if (httpCode < 300 && httpCode >= 200) {
        QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
        QDir dir(path);
        if (!dir.exists()) {
            dir.mkpath(path);
        }

        path += QString("/stations.csv");
        QFile file(path);

        if (!file.open(QIODevice::WriteOnly)) {
            qDebug() << "Error: Couldn't open stations.csv for writing";
        }
        else {
            file.write(reply_stations->readAll());
            file.close();
            bool ok = databaseManager->importStations();
            if (!ok) qDebug() << "Import Failed";
        }
        reply_stations->deleteLater();
    }
}
示例#27
0
void NewstuffModel::retrieveData()
{
    if ( d->m_currentReply && d->m_currentReply->isReadable() ) {
        // check if we are redirected
        const QVariant redirectionAttribute = d->m_currentReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
        if ( !redirectionAttribute.isNull() ) {
            d->m_currentReply = d->m_networkAccessManager.get( QNetworkRequest( redirectionAttribute.toUrl() ) );
            QObject::connect( d->m_currentReply, SIGNAL(readyRead()), this, SLOT(retrieveData()) );
            QObject::connect( d->m_currentReply, SIGNAL(readChannelFinished()), this, SLOT(retrieveData()) );
            QObject::connect( d->m_currentReply, SIGNAL(downloadProgress(qint64,qint64)),
                              this, SLOT(updateProgress(qint64,qint64)) );
        } else {
            d->m_currentFile->write( d->m_currentReply->readAll() );
            if ( d->m_currentReply->isFinished() ) {
                d->m_currentReply->deleteLater();
                d->m_currentReply = nullptr;
                d->m_currentFile->flush();
                d->installMap();
            }
        }
    }
}
void DefinitionDownloader::run()
{
    Utils::NetworkAccessManager *manager = Utils::NetworkAccessManager::instance();

    int currentAttempt = 0;
    const int maxAttempts = 5;
    while (currentAttempt < maxAttempts) {
        QScopedPointer<QNetworkReply> reply(getData(manager));
        if (reply->error() != QNetworkReply::NoError) {
            m_status = NetworkError;
            return;
        }

        ++currentAttempt;
        QVariant variant = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if (variant.isValid() && currentAttempt < maxAttempts) {
            m_url = variant.toUrl();
        } else if (!variant.isValid()) {
            saveData(reply.data());
            return;
        }
    }
}
示例#29
0
/**
 * @brief 通过HTTP GET发送URL,因为QNetWorkAccessManager默认不CACHE,所以不必设置
 **/
QByteArray WebUtils::getByUrl(const QUrl &url)
{
  QNetworkReply *reply = qnam.get(QNetworkRequest(url));
  QEventLoop loop;
  connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
  loop.exec();

  QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

  // WARNING: taobao only have once redirect url
  if (reply->error()) {
    qDebug() << reply->errorString();
    return "";
  } else if (!redirectionTarget.isNull()) {
    QUrl newUrl = url.resolved(redirectionTarget.toUrl());
    reply->deleteLater();
    return getByUrl(newUrl);
  }

  QByteArray returnStr = reply->readAll();
  reply->deleteLater();
  return returnStr;
}
示例#30
0
void AvatarDownloader::on_queryUserAvatar_finished()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply *>(sender());
    reply->deleteLater();

    if (reply->error()) {
        qDebug() << "[AvatarHost]Error occured: " << reply->errorString();
        fetchUserAvatarEnd(false);
        return;
    }

    // cause we use "default", redirection may occur
    QVariant possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    m_urlRedirectedTo = redirectUrl(possibleRedirectUrl.toUrl(), m_urlRedirectedTo);

    if(!m_urlRedirectedTo.isEmpty()) {
        qDebug() << "[AvatarHost]fetching redirected, url: "
                 << m_urlRedirectedTo.toString();

        QNetworkReply* replyNext = m_net->get(QNetworkRequest(m_urlRedirectedTo));
        connect(replyNext, SIGNAL(finished()), SLOT(on_queryUserAvatar_finished()));
    } else {
        // finally arrive destination...

        // read and save avatar
        QByteArray bReply = reply->readAll();

        if (!save(m_strCurrentUser, bReply)) {
            qDebug() << "[AvatarHost]failed: unable to save user avatar, guid: " << m_strCurrentUser;
            fetchUserAvatarEnd(false);
            return;
        }

        qDebug() << "[AvatarHost]fetching finished, guid: " << m_strCurrentUser;
        fetchUserAvatarEnd(true);
    }
}