当前位置: 首页>>代码示例>>C++>>正文


C++ QNetworkAccessManager类代码示例

本文整理汇总了C++中QNetworkAccessManager的典型用法代码示例。如果您正苦于以下问题:C++ QNetworkAccessManager类的具体用法?C++ QNetworkAccessManager怎么用?C++ QNetworkAccessManager使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QNetworkAccessManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: SIGNAL

void MainWindow::on_otherButton_clicked()
{

    QEventLoop eventLoop;
    // "quit()" the event-loop, when the network request "finished()"
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    QUrl url("https://api.spark.io/v1/devices/53ff70066667574852212067/reading?access_token=94f1858893b749831ee5704732a1814beea6b678");
    QNetworkRequest req(url);
    QNetworkReply *reply = mgr.get(req);
    eventLoop.exec(); // blocks stack until "finished()" has been called

    if (reply->error() == QNetworkReply::NoError) {

        QString strReply = (QString)reply->readAll();
        qDebug() << "Response:" << strReply;
        QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
        QJsonObject jsonObj = jsonResponse.object();
        qDebug() << "result:" << jsonObj["result"].toInt();
        delete reply;
    }
    else {
        //failure
        qDebug() << "Failure" <<reply->errorString();
        delete reply;
    }


/*
    QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    QUrlQuery postData;
    postData.addQueryItem("access_token","94f1858893b749831ee5704732a1814beea6b678");
    postData.addQueryItem("params","l2,HIGH");
    QUrl url("https://api.spark.io/v1/devices/53ff70066667574852212067/led");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,
                      "application/x-www-form-urlencoded");
    networkManager->post(request,postData.toString(QUrl::FullyEncoded).toUtf8());
*/

}
开发者ID:mohsinobaid,项目名称:A-framework-for-IoT,代码行数:41,代码来源:mainwindow.cpp

示例2: QNetworkAccessManager

void StartUpManager::sendStatistics()
{
	QNetworkAccessManager* manager = new QNetworkAccessManager(this);

	//
	// Сформируем uuid для приложения, по которому будем идентифицировать данного пользователя
	//
	QString uuid
			= DataStorageLayer::StorageFacade::settingsStorage()->value(
				  "application/uuid", DataStorageLayer::SettingsStorage::ApplicationSettings);
	DataStorageLayer::StorageFacade::settingsStorage()->setValue(
		"application/uuid", uuid, DataStorageLayer::SettingsStorage::ApplicationSettings);

	//
	// Построим ссылку, чтобы учитывать запрос на проверку обновлений
	//
	QString url = QString("https://kitscenarist.ru/api/app/updates/");

	url.append("?system_type=");
	url.append(
#ifdef Q_OS_ANDROID
				"android"
#elif defined Q_OS_IOS
				"ios"
#else
				QSysInfo::kernelType()
#endif
				);

	url.append("&system_name=");
	url.append(QSysInfo::prettyProductName().toUtf8().toPercentEncoding());

	url.append("&uuid=");
	url.append(uuid);

	url.append("&application_version=");
	url.append(QApplication::applicationVersion());

	QNetworkRequest request = QNetworkRequest(QUrl(url));
	manager->get(request);
}
开发者ID:Roger-Waters,项目名称:KITScenarist,代码行数:41,代码来源:StartUpManager.cpp

示例3: main

int main(int argc, char * argv[])
{
    QCoreApplication a(argc, argv);

    // Attempt to open the local file and read from it
    QLocalFile file;
    if (!file.open()) {
        qCritical("Unable to open local file - is server running?");
        return 1;
    }

    // Parse the JSON to get the port and token
    QJsonObject obj = QJsonDocument::fromJson(file.readAll()).object();
    if (!obj.contains("port") || !obj.contains("token")) {
        qCritical("Malformed JSON in local file.");
        return 1;
    }

    // Create a request to the server, using the provided port and passing the
    // auth token as a custom HTTP header
    QUrl url(QString("http://127.0.0.1:%1/").arg(obj.value("port").toInt()));
    QNetworkRequest request(url);
    request.setRawHeader("X-Auth-Token", obj.value("token").toString().toUtf8());

    // Send the request
    QNetworkAccessManager manager;
    QNetworkReply *reply = manager.get(request);

    // Check the response
    QObject::connect(reply, &QNetworkReply::finished, [&a, reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            qDebug("Successfully authenticated to server.");
            a.exit();
        } else {
            qCritical("Error: %s", reply->errorString().toUtf8().constData());
            a.exit(1);
        }
    });

    return a.exec();
}
开发者ID:Kuipers,项目名称:qhttpengine,代码行数:41,代码来源:client.cpp

示例4: QNetworkAccessManager

void LauncherWindow::startGame() {

    ui->playButton->setEnabled(false);

   QString loginURL ="http://master.ttyh.ru/index.php?act=login";

   QNetworkAccessManager* manager = new QNetworkAccessManager(this);

   // Make login JSON request, see: http://wiki.vg/Authentication
   QJsonDocument data;
   QJsonObject login, agent;
   QNetworkRequest request;

   agent["name"] = "Minecraft";
   agent["version"] = 1;

   login["agent"] = agent;
   login["username"] = ui->nickEdit->text();
   login["password"] = ui->passEdit->text();
   login["clientToken"] = "tok-tok-en";

   data.setObject(login);

   QByteArray postdata;
   postdata.append(data.toJson());

   request.setUrl(loginURL);
   request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
   request.setHeader(QNetworkRequest::ContentLengthHeader, postdata.size());

   QNetworkReply *reply = manager->post(request, postdata);
   QEventLoop loop;
   connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
   // FIXME: no error handler
   loop.exec();

   qDebug() << "Req: " << postdata;
   qDebug() << "Reply: " << reply->readAll();

   ui->playButton->setEnabled(true);
}
开发者ID:DarthMolibden,项目名称:ttyhlauncher,代码行数:41,代码来源:launcherwindow.cpp

示例5: url

void ScriptEditorWidget::loadFile(const QString& scriptPath) {
     QUrl url(scriptPath);

    // if the scheme length is one or lower, maybe they typed in a file, let's try
    const int WINDOWS_DRIVE_LETTER_SIZE = 1;
    if (url.scheme().size() <= WINDOWS_DRIVE_LETTER_SIZE) {
        QFile file(scriptPath);
        if (!file.open(QFile::ReadOnly | QFile::Text)) {
            QMessageBox::warning(this, tr("Interface"), tr("Cannot read script %1:\n%2.").arg(scriptPath)
                                                                                         .arg(file.errorString()));
            return;
        }
        QTextStream in(&file);
        _scriptEditorWidgetUI->scriptEdit->setPlainText(in.readAll());
        setScriptFile(scriptPath);

        if (_scriptEngine != NULL) {
            disconnect(_scriptEngine, &ScriptEngine::runningStateChanged, this, &ScriptEditorWidget::runningStateChanged);
            disconnect(_scriptEngine, &ScriptEngine::errorMessage, this, &ScriptEditorWidget::onScriptError);
            disconnect(_scriptEngine, &ScriptEngine::printedMessage, this, &ScriptEditorWidget::onScriptPrint);
        }
    } else {
        QNetworkAccessManager* networkManager = new QNetworkAccessManager(this);
        QNetworkReply* reply = networkManager->get(QNetworkRequest(url));
        qDebug() << "Downloading included script at" << scriptPath;
        QEventLoop loop;
        QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
        loop.exec();
        _scriptEditorWidgetUI->scriptEdit->setPlainText(reply->readAll());
        if (!saveAs()) {
            static_cast<ScriptEditorWindow*>(this->parent()->parent()->parent())->terminateCurrentTab();
        }
    }

    _scriptEngine = Application::getInstance()->getScriptEngine(_currentScript);
    if (_scriptEngine != NULL) {
        connect(_scriptEngine, &ScriptEngine::runningStateChanged, this, &ScriptEditorWidget::runningStateChanged);
        connect(_scriptEngine, &ScriptEngine::errorMessage, this, &ScriptEditorWidget::onScriptError);
        connect(_scriptEngine, &ScriptEngine::printedMessage, this, &ScriptEditorWidget::onScriptPrint);
    }
}
开发者ID:Bazm0,项目名称:hifi,代码行数:41,代码来源:ScriptEditorWidget.cpp

示例6: provider

/*! \brief Searches for a given show name
    \param showName The show name to search for
    \return A QList of ShowDetail containing the show information of search results
    \sa ShowDetail

    Using QNetworkAccessManager and QNetworkReply, a blocking connection is made
    to an XML service provider (in this case TVRage), for the results of the user
    submitted search.
    Once the XML data is retrived, it is parsed with QXmlStreamReader and
    necessary ShowDetial objects are contructed and returned.
*/
QList< ShowDetail > ShowHolder::Search( QString const& showName )
{
    QEventLoop waitLoop;
    QNetworkAccessManager netManager;
    QNetworkReply* netReply = netManager.get( QNetworkRequest( QUrl( "http://services.tvrage.com/feeds/search.php?show=" + showName ) ) );
    QObject::connect( netReply, SIGNAL( finished() ), &waitLoop, SLOT( quit() ) );
    waitLoop.exec();

    QList< ShowDetail > results;
    QXmlStreamReader xmlData;
    xmlData.addData( netReply->readAll() );

    while( !xmlData.atEnd() )
    {
        if( xmlData.readNextStartElement() )
        {
            if( xmlData.name() == "show" )
                results.append( ShowDetail() );
            else if( xmlData.name() == "showid" )
                results.back().id = xmlData.readElementText().toInt();
            else if( xmlData.name() == "name" )
                results.back().name = xmlData.readElementText();
            else if( xmlData.name() == "started" )
                results.back().start = xmlData.readElementText();
            else if( xmlData.name() == "ended" )
                results.back().end = xmlData.readElementText();
            else if( xmlData.name() == "status" )
                results.back().status = xmlData.readElementText();
            else if( xmlData.name() == "genre" )
            {
                if( !results.back().genre.isEmpty() )
                    results.back().genre += "; ";
                results.back().genre += xmlData.readElementText();
            }
        }
    }

    netReply->deleteLater();

    return results;
}
开发者ID:TimJones,项目名称:RenameTV,代码行数:52,代码来源:showholder.cpp

示例7: QString

void CmdCamUpdatePreviewHandler::handle(QJsonObject obj, IWebSocketClient *wsc){
	// TODO
	if(QFile::exists("preview.jpg"))
		QFile::remove("preview.jpg");

	QString preview_command = wsc->settings()->streams_preview_command();
	preview_command.replace(QString("%PREVIEWJPG%"), QString("preview.jpg"));
	qDebug() << "[WS] create preview: " << preview_command;
	
	QProcess process;
	process.start(preview_command);
	process.waitForFinished(-1);

	QString upload_url = "http://" + wsc->settings()->servercm_upload_url() + "/" + wsc->settings()->camera_media_url();
	upload_url += "?sid=" + wsc->settings()->servercm_sid();
	upload_url += "&cat=" + MediaServerInfo::upload_cat_preview();
	upload_url += "&type=" + MediaServerInfo::upload_ftype_jpg();
	upload_url += "&start=" + QDateTime::currentDateTime().toString("yyyyMMddThhmmss.zzz");
	
	qDebug() << "[WS] upload_url: " << upload_url;
	
	QNetworkRequest request(upload_url);
	request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
	request.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"preview\"; filename=\"preview.jpg\""));

	QFile *file = new QFile("preview.jpg");
	if (!file->exists()) {
		qDebug() << "[WS] Upload Error. File does not exist: preview.jpg";
		return;
	}
	file->open(QIODevice::ReadOnly);

	QNetworkAccessManager *networkManager = new QNetworkAccessManager();
	QNetworkReply *pReply = networkManager->post(request, file);

	// QEventLoop eventLoop;
	// QObject::connect(pReply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
	// eventLoop.exec();

	wsc->sendMessage(wsc->makeCommandDone(cmd(), obj["msgid"].toInt(), "OK"));
}
开发者ID:VideoExpertsGroup,项目名称:CloudVideoPlatform,代码行数:41,代码来源:cmd_cam_update_preview_handler.cpp

示例8: connect

void
StravaDialog::requestVerifyUpload()
{
    progressBar->setValue(0);
    progressLabel->setText(tr("Ride processing..."));

    QEventLoop eventLoop;
    QNetworkAccessManager networkMgr;

    connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestVerifyUploadFinished(QNetworkReply*)));
    connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));
    QByteArray out;


    QUrl url = QUrl(STRAVA_URL2 + "/upload/status/"+uploadId+"?token="+token);
    QNetworkRequest request = QNetworkRequest(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    networkMgr.post( request, out);
    eventLoop.exec();
}
开发者ID:ss173b,项目名称:GoldenCheetah,代码行数:21,代码来源:StravaDialog.cpp

示例9: parseLiveVideoPage

void YouTube::parseLiveVideoPage(QNetworkReply *reply) {
    QNetworkAccessManager *manager = qobject_cast<QNetworkAccessManager*>(sender());

    QByteArray response = reply->readAll();
    response = QByteArray::fromPercentEncoding(response.simplified().replace(QByteArray(" "), QByteArray("")));
//    qDebug() << response;
    int pos = response.indexOf("fmt_stream_map=") + 18;
    int pos2 = response.indexOf('|', pos);
    response = response.mid(pos, pos2 - pos);
    QByteArray videoUrl = response.replace(QByteArray("\\/"), QByteArray("/")).replace(QByteArray("\\u0026"), QByteArray("&")).replace(QByteArray("%2C"), QByteArray(","));
    if (!(videoUrl.startsWith("http"))) {
        emit alert(tr("Error: Unable to retrieve video"));
        emit videoUrlError();
    }
    else {
        emit gotVideoUrl(QString(videoUrl));
    }
//        qDebug() << videoUrl;
    reply->deleteLater();
    manager->deleteLater();
}
开发者ID:cuiboand1,项目名称:ytd-meego,代码行数:21,代码来源:youtube.cpp

示例10: qDebug

/*!
\brief Ziska seznam zdroju, ve kterych jsou neprectene polozky
*/
void GoogleReader::getUnreadFeeds() {
    qDebug() << "GoogleReader::getUnreadFeeds()";

    if (_googleCookie == NULL) {
        emit signalConnected(false);
        this->login();
    }

    QNetworkAccessManager* managerGetUnreadFeeds = new QNetworkAccessManager(this);
    QString unixTime = QString::number(getUnixTime());

    QString feedUrl = QString("http://www.google.com/reader/api/0/unread-count?allcomments=true&output=xml&ck=%1&client=GooDer").arg(unixTime);

    QNetworkRequest getRequest= QNetworkRequest(QUrl(feedUrl));
    getRequest.setRawHeader("Authorization", _googleCookie->value());

    managerGetUnreadFeeds->get(getRequest);

    connect(managerGetUnreadFeeds, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(parseUnreadFeeds(QNetworkReply*)));
}
开发者ID:tpopela,项目名称:GooDer,代码行数:24,代码来源:googleReader.cpp

示例11: QNetworkAccessManager

void DataLoader::loadConnections(QString from, QString to, QDateTime time){
	QNetworkAccessManager* netManager = new QNetworkAccessManager();
	if (!netManager)
	{
		qDebug() << "Unable to create QNetworkAccessManager!";
		emit connectionsLoaded("Unable to create QNetworkAccessManager!", false);
		return;
	}

	QString queryUri = "http://transport.opendata.ch/v1/connections?";
	queryUri += "from=" + from;
	queryUri += "&to=" + to;
	queryUri += "&date=" + time.toString("yyyy-MM-dd");
	queryUri += "&time=" + time.toString("hh:mm");
	queryUri += "&limit=5";
	QUrl url(queryUri);
	QNetworkRequest req(url);

	connect(netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onConnectionsReply(QNetworkReply*)));
	QNetworkReply* ipReply = netManager->get(req);
}
开发者ID:m-kay,项目名称:timetable,代码行数:21,代码来源:DataLoader.cpp

示例12: QNetworkAccessManager

void ElisaServer::report(QString id)
{
    //check if user is already logged
    if(m_nickname!=""){
        QNetworkAccessManager *manager = new QNetworkAccessManager(this);

        //set urls
        QUrl url;
        url.setUrl("http://projectelisa.altervista.org/main/report/?target="+id);

        //bind network request
        QNetworkRequest request;
        request.setUrl(url);

        //define callback
        QNetworkReply * r;
        r = manager->get(request);
        connect(r,SIGNAL(finished()),this,SLOT(reportFinished()));
    } else {
    }
}
开发者ID:LucaFos,项目名称:projectelisa-qt,代码行数:21,代码来源:elisaserver.cpp

示例13: QByteArray

QByteArray Toxme::makeJsonRequest(QString url, QString json, QNetworkReply::NetworkError &error)
{
    if (error)
        return QByteArray();

    QNetworkAccessManager netman;
    netman.setProxy(Settings::getInstance().getProxy());
    QNetworkRequest request{url};
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QNetworkReply* reply = netman.post(request, json.toUtf8());

    while (!reply->isFinished())
    {
        QThread::msleep(1);
        qApp->processEvents();
    }

    QByteArray result = reply->readAll();
    delete reply;
    return result;
}
开发者ID:Artom-Kozincev,项目名称:qTox,代码行数:21,代码来源:toxme.cpp

示例14: QNetworkAccessManager

QString ApiEntryPrivate::requestUrl(const QString& strUrl)
{
    QNetworkAccessManager* net = new QNetworkAccessManager();
    QNetworkReply* reply = net->get(QNetworkRequest(strUrl));

    CWizAutoTimeOutEventLoop loop(reply);
    loop.exec(QEventLoop::ExcludeUserInputEvents);    

    if (loop.timeOut())
        return NULL;

    if (loop.error() != QNetworkReply::NoError)
        return NULL;

    //NOTE: reply has been delete in event loop, should not be deleted here
//    reply->deleteLater();

    net->deleteLater();

    return loop.result();
}
开发者ID:rokite,项目名称:WizQTClient,代码行数:21,代码来源:apientry.cpp

示例15: QUrl

/**
*	@brief Check wether the user password is correct
*
*	@see 	signal authentificationResponse(bool response)
*
*	@param  QString userName			the user name
*	@param  QString userPassword		the user password
*/
void ImageShackUploader::checkUserPassword(QString	userName    ,
        QString  userPassword)
{
    QUrl url = QUrl(authentificationUrl + "?username=" + userName + "&password=" + userPassword + "&nocookie=1&format=xml");

    QNetworkRequest request(url);
    QNetworkAccessManager * manager = new QNetworkAccessManager;

    this->uploadAborted = false;

    // manage proxy
    if(this->proxy != NULL)
        manager->setProxy(*this->proxy);

    this->networkReply = manager->get(request);

    connect(this->networkReply, SIGNAL(error(QNetworkReply::NetworkError)),
            this , SLOT(manageUploadError(QNetworkReply::NetworkError)));

    connect(this->networkReply, SIGNAL(finished()), this, SLOT(manageAuthentificationResponse()));
}
开发者ID:Supm4n,项目名称:ImageShackUploader,代码行数:29,代码来源:ImageShackUploader.cpp


注:本文中的QNetworkAccessManager类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。