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());
*/

}
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);
}
示例#3
0
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();
}
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);
}
示例#5
0
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);
    }
}
示例#6
0
/*! \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;
}
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"));
}
示例#8
0
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();
}
示例#9
0
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();
}
示例#10
0
/*!
\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*)));
}
示例#11
0
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);
}
示例#12
0
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 {
    }
}
示例#13
0
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;
}
示例#14
0
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();
}
/**
*	@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()));
}
void CWizEmailShareDialog::on_toolButton_send_clicked()
{
    Q_ASSERT(!m_note.strGUID.isEmpty());

    QString strToken = WizService::Token::token();
    QString strKS = WizService::ApiEntry::kUrlFromGuid(strToken, m_note.strKbGUID);
    QString strExInfo = getExInfo();
    QString strUrl = WizService::ApiEntry::mailShareUrl(strKS, strExInfo);
//    strUrl += strExInfo;

//    QUrl url(strKS);
//    strUrl.remove("http://{ks_host}");
//    strUrl = url.scheme() + "://" + url.host() + strUrl;



    QNetworkAccessManager net;
    QNetworkReply* reply = net.get(QNetworkRequest(strUrl));

//    QEventLoop loop;
    QMessageBox msgBox(this);
    msgBox.setText(tr("Sending..."));
    msgBox.setWindowTitle(tr("Info"));
    connect(reply, SIGNAL(finished()), &msgBox, SLOT(accept()));
    msgBox.exec();

    if (reply->error() != QNetworkReply::NoError) {
        QMessageBox::information(this, tr("Info"), reply->errorString());
        reply->deleteLater();
        return;
    }

    QString strReply = QString::fromUtf8(reply->readAll());
    int nCode;
    QString returnMessage;
    processReturnMessage(strReply, nCode, returnMessage);
    mailShareFinished(nCode, returnMessage);

    reply->deleteLater();
}
示例#17
0
  std::pair<QNetworkReply::NetworkError, QString> NetworkProxyDialog::testProxyConnection(const QNetworkProxy &t_proxy, QWidget *t_parent)
  {
    QProgressDialog dlg("Verifying Proxy Connection", "Cancel",0, 1000, t_parent);
    dlg.setWindowModality(Qt::WindowModal);
    dlg.setValue(0);
    dlg.setMinimumDuration(1000);

    QNetworkAccessManager nam;
    nam.setProxy(t_proxy);
    QNetworkReply *head = nam.head(QNetworkRequest(QUrl("https://bcl.nrel.gov/")));

    if (!head) return std::make_pair(QNetworkReply::UnknownNetworkError, QString("Unknown error creating connection to proxy."));

    boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time();
    while ( !head->isFinished()
            && (boost::posix_time::microsec_clock::universal_time() - start).total_milliseconds() < 10000
            && !dlg.wasCanceled())
    {
      int time = (boost::posix_time::microsec_clock::universal_time() - start).total_milliseconds();
      dlg.setValue(time);
      if (time >= 950 && dlg.maximum() < 10000)
      {
        dlg.setMaximum(10000);
      }
    }
    dlg.reset();
    Application::instance().processEvents();

    head->deleteLater();

    if (!head->isFinished()) 
    {
      head->abort();
      return std::make_pair(QNetworkReply::TimeoutError, QString("Timed out while attempting to verify proxy connection"));
    }

    LOG(Debug, " errorString from proxy test " << toString(head->errorString()) << " " << head->error());

    return std::make_pair(head->error(), head->errorString());
  }
示例#18
0
文件: main.cpp 项目: betaY/crawler
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QNetworkRequest req;
    QUrl *login_url = new QUrl("https://www.secure.pixiv.net/login.php?return_to=%2F");
    req.setUrl(*login_url);
    req.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36");
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QNetworkAccessManager man;
    QNetworkCookieJar *cookies = new QNetworkCookieJar();
    man.setCookieJar(cookies);

    QByteArray *data = new QByteArray();
    data->append("mode=login&return_to=http%3A%2F%2Fwww.pixiv.net%2F&pixiv_id=beta168921%40gmail.com&pass=xjy168921&skip=1");
    QNetworkReply *reply = man.post(req,*data);

    QObject::connect(reply,&QNetworkReply::finished, [&reply, &man](){
        QTextStream qerr(stderr);
        QList<QNetworkReply::RawHeaderPair> headers(reply->rawHeaderPairs());
        for (int i = 0; i < headers.size(); ++i)
        {
            qerr << "HEADER: " << headers[i].first << " CONTENT: " << headers[i].second << "\n";
        }
//        man(reply->manager());
//        qerr << "\n\n";
//        QList<QNetworkCookie> cookie(man->cookieJar()->cookiesForUrl(QUrl("http://www.pixiv.net")));
//        for (int i = 0; i > cookie.size(); ++i) {
//            qerr << cookie[i].toRawForm();
//        }
//        qerr << man.cookieJar()->cookiesForUrl(QUrl("http://www.pixiv.net"));
    });

//    QTextStream qerr(stderr);



    return a.exec();
}
示例#19
0
QString MLNetwork::httpGetBinaryFile(const QString& url)
{
    if (MLUtil::inGuiThread()) {
        qCritical() << "Cannot call MLNetwork::httpGetBinaryFile from within the GUI thread: " + url;
        exit(-1);
    }

    //TaskProgress task("Downloading binary file");
    //task.log(url);
    QTime timer;
    timer.start();
    QString fname = get_temp_fname();
    QNetworkAccessManager manager; // better make it a singleton
    QNetworkReply* reply = manager.get(QNetworkRequest(QUrl(url)));
    QEventLoop loop;
    QFile temp(fname);
    int num_bytes = 0;
    temp.open(QIODevice::WriteOnly);
    QObject::connect(reply, &QNetworkReply::readyRead, [&]() {
        if (MLUtil::threadInterruptRequested()) {
            TaskProgress errtask("Download halted");
            errtask.error("Thread interrupt requested");
            errtask.log(url);
            reply->abort();
        }
        QByteArray X=reply->readAll();
        temp.write(X);
        num_bytes+=X.count();
    });
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    //task.setLabel(QString("Downloaded %1 MB in %2 sec").arg(num_bytes * 1.0 / 1e6).arg(timer.elapsed() * 1.0 / 1000));
    printf("RECEIVED BINARY (%d ms, %d bytes) from %s\n", timer.elapsed(), num_bytes, url.toLatin1().data());
    TaskManager::TaskProgressMonitor::globalInstance()->incrementQuantity("bytes_downloaded", num_bytes);
    if (MLUtil::threadInterruptRequested()) {
        return "";
    }
    return fname;
}
示例#20
0
 // Connect to API, and test if the URL is working
void ApiFuncs::ConnectToApi(QString a_filename, QString a_url, bool &a_errorTest, QString a_search)
{
    // If the given cache-file not exists and is old, get a new one. If else, do nothing
    if (this->fileFuncs->CheckIfFileExists(a_filename) == false || this->fileFuncs->CheckIfFileIsTheLatest(a_filename) == false)
    {
        // Do a bunch of stuff for setting up a connection
        // with reponse and reply
        QNetworkRequest networkRequest;
        networkRequest.setUrl(QUrl(a_url));
        QNetworkAccessManager *networkManager = new QNetworkAccessManager();
        QNetworkReply *networkReply = networkManager->get(networkRequest);
        QEventLoop loop;

        // Check if the download of data from the connection is done
        connect(networkReply, SIGNAL(finished()), &loop, SLOT(quit())); // A sort of eventlistener for signal/slots

        // Check if the there was an error
        connect(networkReply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit())); // A sort of eventlistener for signal/slots
        loop.exec();

        // If there was an error, set the test for it to false
        // and send it back with the callback in the method-parameters,
        // to the mainwindow-class.
        if (networkReply->error())
        {
            a_errorTest = false;
            disconnect(networkReply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit())); // Remove eventlistener
        }

        // If the download of data from the connection was done,
        // load the method for saving the data to a given cache-file
        else if (networkReply->isFinished())
        {
            this->SaveApiData(a_filename, networkReply->readAll(), a_search);
            disconnect(networkReply, SIGNAL(finished()), &loop, SLOT(quit())); // Remove eventlistener
            loop.quit();
        }
    }
}
示例#21
0
        QString Helpers::postResponse(const QString& url, const QString& data)
        {
            // create custom temporary event loop on stack
            QEventLoop eventLoop;

            // "quit()" the event-loop, when the network request "finished()"
            QNetworkAccessManager mgr;
            QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

            // the HTTP request
            QNetworkRequest req(url);
            QNetworkReply* reply;
            reply = mgr.post(req, data.toLatin1());

            eventLoop.exec(); // blocks stack until "finished()" has been called
            auto success = reply->error() == QNetworkReply::NoError;
            if (!success) {
                sLogger.error("Failure: " + reply->errorString());
                throw new Exception(QString("Failed to performe web request to %1: %2").arg(url).arg(reply->errorString()));
            }
            return reply->readAll();
        }
    void Manager::downloadRegistry(const QUrl &url, const QString &file)
    {
        QNetworkAccessManager network;

        // QNAM is non-blocking / non-synchronous, but we want to wait until reply has
        // been received
        // create custom temporary event loop on stack to block the stack until
        // finished received
        QEventLoop eventLoop;

        // "quit()" the event-loop, when the network request "finished()"
        QObject::connect(&network, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));

        // the HTTP request
        QNetworkRequest req(url);
        QNetworkReply *updateCheckResponse = network.get(req);

        // run event loop, which blocks the stack, until "finished()" has been called
        eventLoop.exec();

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

            // read response and parse JSON
            QString strReply           = (QString)updateCheckResponse->readAll();
            QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());

            // save JSON to file
            File::JSON::save(jsonResponse, file);
        } else {
            // QNetworkReply::HostNotFoundError
            qDebug() << "Request Failure: " << updateCheckResponse->errorString();

            QMessageBox::critical(QApplication::activeWindow(), "Request Failure", updateCheckResponse->errorString(),
                                  QMessageBox::Ok);
        }

        // cleanup pointer
        delete updateCheckResponse;
    }
示例#23
0
/*!
\brief Remove feed from subscribe list
*/
void GoogleReader::removeFeed(QString feedId) {
    qDebug() << "GoogleReader::removeFeed(" << feedId << ")";

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

    QString url = "http://www.google.com/reader/api/0/subscription/edit?client=GooDer";
    QString postData = QString("s=feed/%1&ac=unsubscribe&T=%2").arg(feedId, _googleToken);

    QNetworkRequest postRequest = QNetworkRequest(QUrl(url));
    postRequest.setRawHeader("Authorization", _googleCookie->value());
    postRequest.setRawHeader("Content-Type", "application/x-www-form-urlencoded");

    QNetworkAccessManager* managerRemoveFeed = new QNetworkAccessManager(this);

    connect(managerRemoveFeed, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(parseRemoveFeed(QNetworkReply *)));

    managerRemoveFeed->post(postRequest, postData.toAscii());
}
示例#24
0
文件: HttpClient.cpp 项目: xtuer/Qt
// 使用 GET 进行下载,当有数据可读取时回调 readyRead(), 大多数情况下应该在 readyRead() 里把数据保存到文件
void HttpClient::download(std::function<void (const QByteArray &)> readyRead,
                          std::function<void (const QString &)> successHandler,
                          std::function<void (const QString &)> errorHandler) {
    bool debug = d->debug;
    bool internal;
    QNetworkAccessManager *manager = HttpClientPrivate::getManager(d, &internal);
    QNetworkRequest        request = HttpClientPrivate::createRequest(d, HttpClientPrivate::GET);
    QNetworkReply           *reply = manager->get(request);

    // 有数据可读取时回调 readyRead()
    QObject::connect(reply, &QNetworkReply::readyRead, [=] {
        readyRead(reply->readAll());
    });

    // 请求结束
    QObject::connect(reply, &QNetworkReply::finished, [=] {
        QString successMessage = "下载完成"; // 请求结束时一次性读取所有响应数据
        QString errorMessage   = reply->errorString();
        HttpClientPrivate::handleFinish(debug, successMessage, errorMessage, successHandler, errorHandler,
                                        reply, internal ? manager : nullptr);
    });
}
示例#25
0
void WizCommentQuerier::run()
{
    if (m_type == QueryNone)
        return;

    QString token = WizToken::token();
    QString commentsUrl =  WizCommonApiEntry::commentUrl(token, m_kbGUID, m_GUID);
    if (commentsUrl.isEmpty() || token.isEmpty())
    {
        qDebug() << "Can not get comment url by token : " << token;
        errorOccurred();
        return;
    }
    else if (QueryUrl == m_type || QueryUrlAndCount == m_type)
    {
        setCommentsUrl(commentsUrl);
    }

    if (QueryCount != m_type && QueryUrlAndCount != m_type)
        return;

    QString kUrl = WizCommonApiEntry::kUrlFromGuid(token, m_kbGUID);
    QString strCountUrl = WizCommonApiEntry::commentCountUrl(kUrl, token, m_kbGUID, m_GUID);

    QNetworkAccessManager net;
    QNetworkReply* reply = net.get(QNetworkRequest(strCountUrl));

    WizAutoTimeOutEventLoop loop(reply);
    loop.exec();

    if (loop.error() != QNetworkReply::NoError)
    {
        setCommentsCount(0);
        return;
    }

    QString result = QString::fromUtf8(loop.result().constData());
    parseReplyData(result);
}
QByteArray MarketSession::executeRawHttpsQuery(const QByteArray &request)
{
    QByteArray data;
    QUrl url("https://android.clients.google.com/market/api/ApiRequest");
    QNetworkAccessManager manager;
    QNetworkRequest req;
    req.setUrl(url);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    req.setRawHeader("Cookie",QString("ANDROIDSECURE=%1").arg(authSubToken).toUtf8());
    req.setRawHeader("User-Agent", "Android-Market/2 (sapphire PLAT-RC33); gzip");
    req.setRawHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");

    QString requestData=QString("version=%1&request=%2")
            .arg(PROTOCOL_VERSION).arg(QString(request.toBase64()));
    QNetworkReply* http = manager.post(req,requestData.toUtf8());
    QEventLoop eventLoop;
    connect(http,SIGNAL(finished()),&eventLoop, SLOT(quit()));
    eventLoop.exec();
    data=gzipDecompress(http->read(http->header(QNetworkRequest::ContentLengthHeader).toUInt()));
    delete http;
    return data;
}
示例#27
0
receiver::receiver(QObject *parent) : QObject(parent)
{

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));


//    QNetworkRequest request;
//    request.setUrl(QUrl("http://qt-project.org"));
//    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");

    thread()->sleep(1);

    QNetworkReply *reply = manager->get((QNetworkRequest(QUrl("localhost:9998"))));
    connect(reply, SIGNAL(readyRead()), this, SLOT(readyRead()));

    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(slotError(QNetworkReply::NetworkError)));
//    connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
//            this, SLOT(slotSslErrors(QList<QSslError>)));
}
示例#28
0
void
StravaDialog::requestSearchRide()
{
    progressBar->setValue(0);
    progressLabel->setText(tr("Searching corresponding Ride"));

    QEventLoop eventLoop;
    QNetworkAccessManager networkMgr;

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


    QUrl url = QUrl(STRAVA_URL1 + "rides?athleteId="+athleteId+"&startDate="+ride->ride()->startTime().toString("yyyy-MM-dd")+"&endDate="+ride->ride()->startTime().addDays(1).toString("yyyy-MM-dd"));

    QNetworkRequest request = QNetworkRequest(url);
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    networkMgr.get(request);
    eventLoop.exec();
}
示例#29
0
void GoodbyeSender::send(){
	QNetworkAccessManager *m = new QNetworkAccessManager(this);

	QNetworkRequest request(getURL());
	if(request.url().toString() == "/"){
		emit errored();
		return;
	}

	request.setRawHeader("User-Agent", "RuleCreator");
	request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

	QByteArray data;
	QUrl params;

	params.addQueryItem("playerName", _target.playerName);
	params.addQueryItem("tableName", _target.tableName);
	data = params.encodedQuery();

	reply = m->post(request, data);
	connect(reply, SIGNAL(finished()), this, SLOT(finish()));
}
示例#30
0
/*!
\brief Get list of all entries
*/
void GoogleReader::getEntries() {
    qDebug() << "GoogleReader::getEntries()";

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

    QString feedUrl;
    int numberOfEntries = 1000;

    QNetworkAccessManager* managerGetEntriesList = new QNetworkAccessManager(this);
    feedUrl = QString("http://www.google.com/reader/atom/user/-/state/com.google/reading-list?n=%1").arg(numberOfEntries);

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

    connect(managerGetEntriesList, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(parseEntries(QNetworkReply*)));

    managerGetEntriesList->get(getRequest);
}