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


C++ QNetworkReply::deleteLater方法代码示例

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


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

示例1: req

void
NwReqTracker::onReplyFinished()
{
    replyTimer.stop ();

    bool rv = false, done = false;
    QByteArray response;
    QNetworkReply *origReply = reply;

    do { // Begin cleanup block (not a loop)
        if (aborted) {
            Q_WARN("Reply was aborted");
            break;
        }

        if (QNetworkReply::NoError != origReply->error ()) {
            Q_WARN("Response error: ") << origReply->errorString ();
            break;
        }

        response = origReply->readAll ();
        rv = true;
    } while (0); // End cleanup block (not a loop)

    do { // Begin cleanup block (not a loop)
        done = true;

        if (!rv) {
            break;
        }

        if (!autoRedirect) {
            break;
        }

        QUrl urlMoved = hasMoved (origReply);
        if (urlMoved.isEmpty ()) {
            break;
        }

        QNetworkRequest req(urlMoved);
        req.setRawHeader("User-Agent", uaString);

        NwReqTracker::setCookies (jar, req);
        QNetworkReply *nextReply = nwMgr.get(req);
        if (!nextReply) {
            break;
        }

        disconnectReply ();
        init (nextReply, ctx, emitLog, autoDelete);
        autoRedirect = true;

        done = false;
    } while (0); // End cleanup block (not a loop)

    if (done) {
        if (!autoRedirect && response.contains ("Moved Temporarily")) {
            QString msg = "Auto-redirect not requested, but page content "
                          "probably indicates that this page has been "
                          "temporarily moved. Original request = %1";

            msg = msg.arg (origReply->request().url().toString ());

            QString strResp = response;
            int pos = strResp.indexOf ("a href=", 0, Qt::CaseInsensitive);
            if (-1 != pos) {
                int endpos = strResp.indexOf ("</a>", pos, Qt::CaseInsensitive);
                if (-1 != endpos) {
                    msg += "\nRedirect URL = " + strResp.mid(pos+8, endpos-pos);
                }
            }

            Q_WARN(msg);
        }

        emit sigDone (rv, response, origReply, ctx);
    }

    origReply->deleteLater ();
    if (done && autoDelete) {
        this->deleteLater ();
    }
}//NwReqTracker::onReplyFinished
开发者ID:pratikmallya,项目名称:qgvdial,代码行数:84,代码来源:NwReqTracker.cpp

示例2: AuthorByRenren

bool autobots_toutiao::AuthorByRenren(const QString& name, const QString& password)
{
	//1.检验验证码
	QString vcode, code_sign;
	bool need_code = NeedValidateCode(name, vcode, code_sign);
	QString str_need_code = need_code ? "true" : "";

	QString str_url1 = "https://graph.renren.com/oauth/grant";

	QUrl url1(str_url1);

	QString str_temp = "http://graph.renren.com/oauth/grant?client_id=" + m_client_id + "&redirect_uri=http://api.snssdk.com/auth/login_success/&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000";

	HttpParamList header_list;
	//header_list.push_back(HttpParamItem("(Request-Line)",	"GET /auth/connect/?type=toutiao&platform=renren_sns HTTP/1.1"));
	header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
	header_list.push_back(HttpParamItem("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-CN"));
	header_list.push_back(HttpParamItem("Host", "graph.renren.com"));
	header_list.push_back(HttpParamItem("Referer", str_temp));
	//Referer	
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));

	HttpParamList post_data;
	QString t = QString("http://api.snssdk.com/auth/login_success/") + "&client_id=" + m_client_id;
	//post_data.push_back(HttpParamItem("authFeed","true"));
	post_data.push_back(HttpParamItem("authorizeOrigin", "00000"));
	//post_data.push_back(HttpParamItem("client_id", m_client_id));
	post_data.push_back(HttpParamItem("display", "touch"));
	post_data.push_back(HttpParamItem("follow", "true"));
	post_data.push_back(HttpParamItem("icode", vcode));
	post_data.push_back(HttpParamItem("isNeedIcode", str_need_code));
	post_data.push_back(HttpParamItem("login_type", "false"));
	post_data.push_back(HttpParamItem("password", password));
	post_data.push_back(HttpParamItem("porigin", "80103"));
	post_data.push_back(HttpParamItem("post_form_id", m_post_id));
	post_data.push_back(HttpParamItem("redirect_uri", t));
	post_data.push_back(HttpParamItem("response_type", "code"));
	post_data.push_back(HttpParamItem("scope", "status_update photo_upload create_album"));
	post_data.push_back(HttpParamItem("secure", "true"));
	post_data.push_back(HttpParamItem("state", m_state_id));
	post_data.push_back(HttpParamItem("username", name));

	QNetworkReply* reply = network.PostRequest_ssl(url1, header_list, post_data);

	QTime _t;
	_t.start();

	bool _timeout = false;

	while (reply && !reply->isFinished())
	{
		QCoreApplication::processEvents();
		if (_t.elapsed() >= TIMEOUT) {
			_timeout = true;
			break;
		}
	}

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

	QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

	int n = statusCodeV.toInt();

	bool res = false;
	if (n == 302 || n == 301)
	{
		// 重定向
		QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

		QUrl red_url = redirectionTarget.toUrl();

		QString str = red_url.toString();

		int r = ProcessRedirectLoginGet(str);

		if (r == 0)
		{
			res = true;
		}
		else if (r == -2)
		{
			// 验证码错误
			VlidateCodeOnLine* obj = VlidateCodeOnLine::GetInstance();
			obj->ReportError("bestsalt", code_sign);
		}
	}
	else
	{
		QString msg = reply->readAll();
		res = false;
	}

	if (reply != NULL)
	{
//.........这里部分代码省略.........
开发者ID:blacksjt,项目名称:autobots,代码行数:101,代码来源:autobots_toutiao.cpp

示例3: processSubscribeDanmakuResponse

void SubscribeThread::processSubscribeDanmakuResponse()
{

    QNetworkReply *reply = (QNetworkReply *)sender();
    int statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
    if(reply->hasRawHeader("Location")){
        QString strLocation = reply->header(QNetworkRequest::LocationHeader).toString();

        this->subscribeDanmaku(strLocation);

    }else if(statusCode == 200){

        QByteArray responseData = reply->readAll();
//        qDebug()<<"response data:"<<responseData;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        if(jsonDoc.isNull() ||!jsonDoc.isArray())
        {//  null or not array format
            goto out;
        }
        QJsonArray jsonArray = jsonDoc.array();
        for(int i = 0; i < jsonArray.count();i++){
            QJsonValue jsonValue = jsonArray[i];
            if(jsonValue.isUndefined()||jsonValue.isNull())
            {
                goto out;
            }
            QString text = jsonValue.toObject().value("text").toString();
            QString position = jsonValue.toObject().value("position").toString();
            QString style = jsonValue.toObject().value("style").toString();


            if(text.size()>128){
                text.resize(128);
            }
            Danmaku_Msg msg;
            msg.msg = text;
            if(style=="blue"){
                msg.color = QColor("#0000FF");
            }else if(style=="white"){
                msg.color = QColor("#FFFFFF");
            }else if(style=="red"){
                msg.color = QColor("#FF0000");
            }else if(style=="yellow"){
                msg.color = QColor("yellow");
            }else if(style=="cyan"){
                msg.color = QColor("cyan");
            }else if(style=="green"){
                msg.color = QColor("#00FF00");
            }else if(style=="purple"){
                msg.color = QColor("#871F78");
            }else{
                msg.color = QColor("black");
            }



            if(position=="top"){
                msg.positon = BULLET_TOP;
            }else if(position == "bottom")
            {
                msg.positon = BULLET_BOTTOM;
            }else
            {
                msg.positon = BULLET_FLY;
            }

            emit this->receivedDamanku(msg);
        }
    }
out:
    qApp->processEvents(QEventLoop::AllEvents);
    if(reply->error() == QNetworkReply::NoError){
        this->pullDanmaku();
    }else
    {
        QTimer::singleShot(2000,this,SLOT(pullDanmaku()));
    }
    reply->deleteLater();
    return;
}
开发者ID:mengzhaoji,项目名称:Danmaku,代码行数:80,代码来源:subscribethread.cpp

示例4: ProcessRedirectLoginGetTemp

// 0 正常,-1 未知错误, -2 验证码错误
int autobots_toutiao::ProcessRedirectLoginGetTemp(const QString& str)
{
	WaitforSeconds(2);

	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
	header_list.push_back(HttpParamItem("Host", "api.snssdk.com"));
	header_list.push_back(HttpParamItem("Referer", "http://graph.renren.com/oauth/grant?client_id=394e2173327e4ead8302dc27f4ae8879&redirect_uri=http%3A%2F%2Fapi.snssdk.com%2Fauth%2Flogin_success%2F&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000"));
	//header_list.push_back(HttpParamItem("",""));
	header_list.push_back(HttpParamItem("Connection", "keep-alive"));
	header_list.push_back(HttpParamItem("Accept-Encoding", "gzip, deflate"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-CN,zh;q=0.8"));
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));

	QNetworkReply* reply = network.GetRequest(QUrl(str), header_list);

	QTime _t;
	_t.start();

	bool _timeout = false;

	while (reply && !reply->isFinished())
	{
		QCoreApplication::processEvents();

		if (_t.elapsed() >= TIMEOUT) {
			_timeout = true;
			break;
		}
	}

	if (reply == NULL || _timeout)
	{

		reply->deleteLater();
		return -1;
	}

	QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	int n = statusCodeV.toInt();

	if ((reply->error() != QNetworkReply::NoError) && n != 500)
	{
		QString t = reply->errorString();
		return -1;
	}

	int res = -1;
	if (n == 302 || n == 301)
	{
		// 重定向
		QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

		QUrl red_url = redirectionTarget.toUrl();

		QString str2 = red_url.toString();

		res = ProcessRedirectLoginGet2(str2) ? 0 : -1;
	}
	else if (n == 302)
	{
		QString str2 = reply->readAll();
		if (str2.contains(QStringLiteral("验证码错误")))
		{
			res = -2;
		}
	}
	else if (n == 500)
	{
		// 找不到页面
		res = ProcessRedirectLoginGetTemp2(str);
	}

	if (reply != NULL)
	{
		reply->deleteLater();
	}

	return res;
}
开发者ID:blacksjt,项目名称:autobots,代码行数:81,代码来源:autobots_toutiao.cpp

示例5: NeedValidateCode

bool autobots_toutiao::NeedValidateCode(const QString& name, QString& vcode, QString& code_sign)
{
	QString str_url1 = "http://graph.renren.com/icode/check";

	QUrl url1(str_url1);
	QString str_temp = "http://graph.renren.com/oauth/grant?client_id=" + m_client_id + "&redirect_uri=http://api.snssdk.com/auth/login_success/&response_type=code&display=page&scope=status_update+photo_upload+create_album&state=renren_sns__0____toutiao____2__0__24&secure=true&origin=00000";
	HttpParamList header_list;
	header_list.push_back(HttpParamItem("Connection", "Keep-Alive"));
	//  header_list.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
	header_list.push_back(HttpParamItem("Accept-Language", "zh-CN"));
	header_list.push_back(HttpParamItem("Host", "graph.renren.com"));
	header_list.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));
	header_list.push_back(HttpParamItem("Referer", str_temp));
	//network.GetManager().setCookieJar(new QNetworkCookieJar(this));

	HttpParamList post_data;
	post_data.push_back(HttpParamItem("authFeed", "true"));
	post_data.push_back(HttpParamItem("authorizeOrigin", "00000"));
	post_data.push_back(HttpParamItem("client_id", m_client_id));
	post_data.push_back(HttpParamItem("display", "page"));
	post_data.push_back(HttpParamItem("follow", "true"));
	post_data.push_back(HttpParamItem("icode", ""));
	post_data.push_back(HttpParamItem("isNeedIcode", ""));
	post_data.push_back(HttpParamItem("login_type", "false"));
	post_data.push_back(HttpParamItem("password", ""));
	post_data.push_back(HttpParamItem("porigin", "80100"));
	post_data.push_back(HttpParamItem("post_form_id", m_post_id));
	post_data.push_back(HttpParamItem("redirect_uri", "http://api.snssdk.com/auth/login_success/"));
	post_data.push_back(HttpParamItem("response_type", "code"));
	post_data.push_back(HttpParamItem("scope", "status_update photo_upload create_album"));
	post_data.push_back(HttpParamItem("secure", "true"));
	post_data.push_back(HttpParamItem("state", "renren_sns__0____toutiao____2__0__24"));
	post_data.push_back(HttpParamItem("username", name));

	QNetworkReply* reply = network.PostRequest(url1, header_list, post_data);

	QTime _t;
	_t.start();

	bool _timeout = false;

	while (reply && !reply->isFinished())
	{
		QCoreApplication::processEvents();
		if (_t.elapsed() >= TIMEOUT) {
			_timeout = true;
			break;
		}
	}

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

	QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

	int n = statusCodeV.toInt();

	if (n != 200)
	{
		return false;
	}

	QString str = reply->readAll();

	reply->deleteLater();

	if (str.toInt() == 0)
	{
		return false;
	}

	// 获取验证码

	QUrl url2("http://icode.renren.com/getcode.do?t=openplatform");
	HttpParamList header_list2;
	header_list2.push_back(HttpParamItem("Connection", "Keep-Alive"));
	//  header_list2.push_back(HttpParamItem("Accept-Encoding","gzip, deflate"));
	header_list2.push_back(HttpParamItem("Accept-Language", "zh-CN"));
	header_list2.push_back(HttpParamItem("Host", "icode.renren.com"));
	header_list2.push_back(HttpParamItem("User-Agent", m_devices_list[m_device_order]._useragent));
	header_list2.push_back(HttpParamItem("Referer", str_temp));

	QNetworkReply* reply2 = network.GetRequest(url2, header_list2);

	_t.restart();

	_timeout = false;

	while (reply2 && !reply2->isFinished())
	{
		QCoreApplication::processEvents();
		if (_t.elapsed() >= TIMEOUT) {
			_timeout = true;
			break;
		}
	}

	if (reply2 == NULL || (reply2->error() != QNetworkReply::NoError) || _timeout)
//.........这里部分代码省略.........
开发者ID:blacksjt,项目名称:autobots,代码行数:101,代码来源:autobots_toutiao.cpp

示例6: onRequestUsers

void QBNetwork::onRequestUsers() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);

				QFile destFile("app/native/assets/users.json");
				if (!destFile.open(QIODevice::WriteOnly))
					return;
				destFile.write(response.toAscii());
				destFile.close();

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "user") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "id") {
									break;
								}
							}
						}
					}
				}

				successLoad = true;
				emit loadingChanged();
				emit completeLogin();

			}
		} else {
			successLoad = true;
			emit loadingChanged();
			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}
			response =
					tr("Error: %1 status: %2").arg(reply->errorString(),
							reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString());
			showError("QBlox Server Error = " + response);
		}
		reply->deleteLater();
	}
}
开发者ID:QuickBlox,项目名称:quickblox-blackberry10-sdk,代码行数:62,代码来源:QBNetwork.cpp

示例7: onDataReceived

void Twitter::onDataReceived()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    QString response;
    bool success = false;
    if (reply)
    {
        if (reply->error() == QNetworkReply::NoError)
        {
            int available = reply->bytesAvailable();
            if (available > 0)
            {
                int bufSize = sizeof(char) * available + sizeof(char);
                QByteArray buffer(bufSize, 0);
                reply->read(buffer.data(), available);
                response = QString(buffer);
                success = true;
            }
        }
        else
        {
            response =  QString("Error: ") + reply->errorString() + QString(" status:") + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
            emit tweetParseComplete(false, "We can't connect to the internet");
        }
        reply->deleteLater();
    }
    if (success )
    {
    	if (response != "[]") {
    		bb::data::JsonDataAccess jda;
    		QVariant jsonva = jda.loadFromBuffer(response);
    		QVariantMap map = jsonva.toMap();
    		QVariantList results = map.value("results").toList();
    		//okay let's get the news items

    		int numTweets = 0;
    		foreach (QVariant v, results) {
    			QVariantMap map = v.toMap();

    			Tweet *tweet = new Tweet();
    			tweet->parse(v);

    			QVariant q = QVariant::fromValue(tweet);

        		_tweetList.append(q); //to go from a QVariant back to a Tweet* item: Tweet *Tweet = q.value<Tweet*>();

    			QVariantList path;
				path.append(_tweetList.indexOf(q));

				emit  itemAdded (path);
				numTweets++;
    		}

        	if (numTweets > 0) {
        		emit tweetParseComplete(true, "Parsed successfully");
        	} else {
        		if (_tweetList.count() == 0) {
        			emit tweetParseComplete(false, "No Tweets yet");
        		}
        	}
    	}
开发者ID:ekke,项目名称:bb10pulltorefresh,代码行数:61,代码来源:Twitter.cpp

示例8: getUpdateVersion

AutoUpdater::VersionInfo AutoUpdater::getUpdateVersion()
{
    VersionInfo versionInfo;
    versionInfo.timestamp = 0;

    // Updates only for supported platforms
    if (platform.isEmpty())
        return versionInfo;

    if (abortFlag)
        return versionInfo;

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    manager->setProxy(Settings::getInstance().getProxy());
    QNetworkReply* reply = manager->get(QNetworkRequest(QUrl(checkURI)));
    while (!reply->isFinished())
    {
        if (abortFlag)
            return versionInfo;
        qApp->processEvents();
    }

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "getUpdateVersion: network error: " + reply->errorString();
        reply->deleteLater();
        manager->deleteLater();
        return versionInfo;
    }

    QByteArray data = reply->readAll();
    reply->deleteLater();
    manager->deleteLater();
    if (data.size() < (int)(1+crypto_sign_BYTES))
        return versionInfo;

    // Check updater protocol version
    if ((int)data[0] != '3')
    {
        qWarning() << "getUpdateVersion: Bad version " << (uint8_t)data[0];
        return versionInfo;
    }

    // Check the signature
    QByteArray sigData = data.mid(1, crypto_sign_BYTES);
    unsigned char* sig = (unsigned char*)sigData.data();
    QByteArray msgData = data.mid(1+crypto_sign_BYTES);
    unsigned char* msg = (unsigned char*)msgData.data();

    if (crypto_sign_verify_detached(sig, msg, msgData.size(), key) != 0)
    {
        qCritical() << "getUpdateVersion: RECEIVED FORGED VERSION FILE FROM "<<updateServer;
        return versionInfo;
    }

    int sepPos = msgData.indexOf('!');
    versionInfo.timestamp = QString(msgData.left(sepPos)).toInt();
    versionInfo.versionString = msgData.mid(sepPos+1);

    qDebug() << "timestamp:"<<versionInfo.timestamp << ", str:"<<versionInfo.versionString;

    return versionInfo;
}
开发者ID:13983441921,项目名称:qTox,代码行数:63,代码来源:autoupdate.cpp

示例9: run


//.........这里部分代码省略.........
				QVariantMap firstData = geoNames.at(0).toMap();
				int ri = 0, l3 = -1, lt = -1;
				if (ds->taxonomy.category == NULL) {
					ds->taxonomy.category = alloc_taxonomy();
				} else {
					// clear out the data (except for the ocean data)
					int ocean;
					if ((ocean = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN)) > 0) {
						ds->taxonomy.category[0] = ds->taxonomy.category[ocean];
						ds->taxonomy.nr = 1;
					} else {
						// ocean is -1 if there is no such entry, and we didn't copy above
						// if ocean is 0, so the following gets us the correct count
						ds->taxonomy.nr = ocean + 1;
					}
				}
				// get all the data - OCEAN is special, so start at COUNTRY
				for (int j = TC_COUNTRY; j < TC_NR_CATEGORIES; j++) {
					if (firstData[taxonomy_api_names[j]].isValid()) {
						ds->taxonomy.category[ri].category = j;
						ds->taxonomy.category[ri].origin = taxonomy::GEOCODED;
						free((void*)ds->taxonomy.category[ri].value);
						ds->taxonomy.category[ri].value = copy_string(qPrintable(firstData[taxonomy_api_names[j]].toString()));
						ri++;
					}
				}
				ds->taxonomy.nr = ri;
				l3 = taxonomy_index_for_category(&ds->taxonomy, TC_ADMIN_L3);
				lt = taxonomy_index_for_category(&ds->taxonomy, TC_LOCALNAME);
				if (l3 == -1 && lt != -1) {
					// basically this means we did get a local name (what we call town), but just like most places
					// we didn't get an adminName_3 - which in some regions is the actual city that town belongs to,
					// then we copy the town into the city
					ds->taxonomy.category[ri].value = copy_string(ds->taxonomy.category[lt].value);
					ds->taxonomy.category[ri].origin = taxonomy::COPIED;
					ds->taxonomy.category[ri].category = TC_ADMIN_L3;
					ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			} else {
				report_error("geonames.org did not provide reverse lookup information");
				qDebug() << "no reverse geo lookup; geonames returned\n" << fullReply;
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}
		// next check the oceans API to figure out the body of water
		request.setUrl(geonamesOceanURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));
		reply = rgl->get(request);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();
		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing oceans API of geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant oceanObject = obj.value("ocean").toVariant();
			QVariantMap oceanName = oceanObject.toMap();
			if (oceanName["name"].isValid()) {
				int idx;
				if (ds->taxonomy.category == NULL)
					ds->taxonomy.category = alloc_taxonomy();
				idx = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN);
				if (idx == -1)
					idx = ds->taxonomy.nr;
				if (idx < TC_NR_CATEGORIES) {
					ds->taxonomy.category[idx].category = TC_OCEAN;
					ds->taxonomy.category[idx].origin = taxonomy::GEOCODED;
					ds->taxonomy.category[idx].value = copy_string(qPrintable(oceanName["name"].toString()));
					if (idx == ds->taxonomy.nr)
						ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}

clear_reply:
		reply->deleteLater();
	}
	rgl->deleteLater();
}
开发者ID:Brainiarc7,项目名称:subsurface,代码行数:101,代码来源:divesitehelpers.cpp

示例10: inputFile

void SwfToHtml5::process()
{
    m_filesLstWgt->clear();
    m_filesLstWgt->addItems(m_pathToFiles);
    m_pBeginConvertBtn->setEnabled(false);
    m_pLoadFileBtn->setEnabled(false);
    m_pLoadFileBtn->setText("Convertation started!");
    if (m_pathToFiles.size() < 1)
        return;

    for (int i = 0; i < m_pathToFiles.size(); ++i) {
        if (QFileInfo(m_pathToFiles.at(i)).isFile()) {
            QFile inputFile(m_pathToFiles.at(i));
            QByteArray bufBa;
            m_nameOfFile = m_pathToFiles.at(i);
            m_nameOfFile = m_nameOfFile.remove(".swf");
            m_nameOfFile += ".html";
            //read swf file
            if (!inputFile.open(QIODevice::ReadOnly)) {
                qDebug()<<"Could not open the input file\n"<<m_pathToFiles.at(i);
                return;
            } else {
                while(!inputFile.atEnd()) {
                    bufBa += inputFile.readLine();
                }
            }
            bufBa = bufBa.toBase64();
            bufBa = bufBa.replace('+', '-');
            bufBa = bufBa.replace('/', '_');

            QUrl apiUrl("https://www.googleapis.com/rpc?key=AIzaSyCC_WIu0oVvLtQGzv4-g7oaWNoc-u8JpEI");
            QByteArray req = "{ \"apiVersion\": \"v1\",\"method\": \"swiffy.convertToHtml\", \"params\": { \"client\": \"Swiffy Flash Extension\", \"input\": \"$\" } }";
            req = req.replace('$', bufBa);

            QNetworkRequest request(apiUrl);

            QEventLoop eventLoop;

            request.setHeader(QNetworkRequest::ContentTypeHeader, "www.googleapis.com");

            QNetworkAccessManager *manager = new QNetworkAccessManager(this);

            connect(manager, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);

            QNetworkReply *reply = manager->post(request, req);
            eventLoop.exec();

            QString dataFromReply;
            if (reply->error() == QNetworkReply::NoError) {
                dataFromReply = QString::fromUtf8(reply->readAll());
            }
            QByteArray replyBa;
            replyBa.append(dataFromReply);

            QFile replyFile("json.txt");
            replyFile.open(QIODevice::WriteOnly);
            replyFile.write(replyBa);
            replyFile.close();

            QFile jsonFile("json.txt");
            if (jsonFile.open(QIODevice::ReadOnly)) {
                QJsonParseError parseError;
                QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonFile.readAll(), &parseError);
                if (parseError.error == QJsonParseError::NoError) {
                    if(jsonDoc.isObject())
                        parseJSON(jsonDoc.object());
                }
                else
                    qDebug() << "JSON parse error: " << parseError.errorString();
            }
            else
                qDebug() << "json.txt not open";
            reply->deleteLater();
        }
        ++cnt;
    }
    cnt = 0;
    m_pLoadFileBtn->setText("Load files");
    m_pLoadFileBtn->setEnabled(true);
    m_filesLstWgt->addItem("Finished!");
    m_pBeginConvertBtn->setEnabled(true);
}
开发者ID:folax,项目名称:swfToHtml5,代码行数:82,代码来源:swftohtml5.cpp

示例11: updateCamerasReply

void DVRServer::updateCamerasReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply)
        return;

    qDebug() << "DVRServer: Received cameras list reply";

    reply->deleteLater();

    if (reply->error() != QNetworkReply::NoError)
    {
        /* TODO: Handle this well */
        qWarning() << "DVRServer: Error from updating cameras:" << reply->errorString();
        return;
    }

    QByteArray data = reply->readAll();
    QXmlStreamReader xml(data);

    QSet<int> idSet;
    bool hasDevicesElement = false;
    bool wasEmpty = m_visibleCameras.isEmpty();

    while (xml.readNextStartElement())
    {
        if (xml.name() == QLatin1String("devices"))
        {
            hasDevicesElement = true;

            while (xml.readNext() != QXmlStreamReader::Invalid)
            {
                if (xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == QLatin1String("devices"))
                    break;
                else if (xml.tokenType() != QXmlStreamReader::StartElement)
                    continue;

                if (xml.name() == QLatin1String("device"))
                {
                    bool ok = false;
                    QString idv = xml.attributes().value(QLatin1String("id")).toString();
                    if (idv.isNull())
                        continue;
                    int deviceId = (int)idv.toUInt(&ok);
                    if (!ok)
                    {
                        xml.raiseError(QLatin1String("Invalid device ID"));
                        continue;
                    }

                    idSet.insert(deviceId);
                    DVRCamera *camera = getCamera(deviceId);

                    if (camera)
                    {
                        camera->setOnline(true);
                        
                        DVRCameraXMLReader xmlReader;
                        if (!xmlReader.readCamera(camera, xml))
                        {
                            if (!xml.hasError())
                                xml.raiseError(QLatin1String("Device parsing failed"));
                            continue;
                        }
                        else
                        {
                            DVRCameraSettingsWriter settingsWriter;
                            settingsWriter.writeCamera(camera);
                        }
                    }

                    if (!m_visibleCameras.contains(camera))
                    {
                        m_visibleCameras.append(camera);
                        emit cameraAdded(camera);
                    }
                }
            }
            break;
        }
        else
            xml.skipCurrentElement();
    }

    if (!hasDevicesElement)
        xml.raiseError(QLatin1String("Invalid format: no devices element"));

    if (xml.hasError())
    {
        qWarning() << "DVRServer: Error while parsing camera list:" << xml.errorString();
        return;
    }

    for (int i = 0; i < m_visibleCameras.size(); ++i)
    {
        if (!idSet.contains(m_visibleCameras[i]->data().id()))
        {
            DVRCamera *c = m_visibleCameras[i];
            m_visibleCameras.removeAt(i);
            m_camerasMap.remove(c->data().id());
//.........这里部分代码省略.........
开发者ID:chenbk85,项目名称:bluecherry-client,代码行数:101,代码来源:DVRServer.cpp

示例12: GenerateMore

PlaylistItemList SubsonicDynamicPlaylist::GenerateMore(int count) {
  SubsonicService* service = InternetModel::Service<SubsonicService>();
  const int task_id =
      service->app_->task_manager()->StartTask(tr("Fetching Playlist Items"));

  BOOST_SCOPE_EXIT((service)(task_id)) {
    // stop task when we're done
    service->app_->task_manager()->SetTaskFinished(task_id);
  }
  BOOST_SCOPE_EXIT_END

  QUrl url = service->BuildRequestUrl("GetAlbumList");
  QNetworkAccessManager network;

  if (count > kMaxCount) count = kMaxCount;

  url.addQueryItem("type", GetTypeString());
  url.addQueryItem("size", QString::number(count));
  url.addQueryItem("offset", QString::number(offset_));

  PlaylistItemList items;

  QNetworkReply* reply = Send(network, url, service->usesslv3_);
  WaitForSignal(reply, SIGNAL(finished()));

  reply->deleteLater();

  if (reply->error() != QNetworkReply::NoError) {
    qLog(Warning) << "HTTP error returned from Subsonic:"
                  << reply->errorString() << ", url:" << url.toString();
    return items;  // empty
  }

  QXmlStreamReader reader(reply);
  reader.readNextStartElement();
  if (reader.name() != "subsonic-response") {
    qLog(Warning) << "Not a subsonic-response, aboring playlist fetch";
    return items;
  }

  if (reader.attributes().value("status") != "ok") {
    reader.readNextStartElement();
    int error = reader.attributes().value("code").toString().toInt();
    qLog(Warning) << "An error occured fetching data.  Code: " << error
                  << " Message: "
                  << reader.attributes().value("message").toString();
  }

  reader.readNextStartElement();
  if (reader.name() != "albumList") {
    qLog(Warning) << "albumList tag expected.  Aboring playlist fetch";
    return items;
  }

  while (reader.readNextStartElement()) {
    if (reader.name() != "album") {
      qLog(Warning) << "album tag expected. Aboring playlist fetch";
      return items;
    }

    qLog(Debug) << "Getting album: "
                << reader.attributes().value("album").toString();
    GetAlbum(service, items, reader.attributes().value("id").toString(),
             network, service->usesslv3_);
    reader.skipCurrentElement();
  }
  offset_ += count;
  return items;
}
开发者ID:ConfusedGiant,项目名称:Clementine,代码行数:69,代码来源:subsonicdynamicplaylist.cpp

示例13: GetAlbum

void SubsonicDynamicPlaylist::GetAlbum(SubsonicService* service,
                                       PlaylistItemList& list, QString id,
                                       QNetworkAccessManager& network,
                                       const bool usesslv3) {
  QUrl url = service->BuildRequestUrl("getAlbum");
  url.addQueryItem("id", id);
  if (service->IsAmpache()) {
    url.addQueryItem("ampache", "1");
  }
  QNetworkReply* reply = Send(network, url, usesslv3);
  WaitForSignal(reply, SIGNAL(finished()));
  reply->deleteLater();

  if (reply->error() != QNetworkReply::NoError) {
    qLog(Warning) << "HTTP error returned from Subsonic:"
                  << reply->errorString() << ", url:" << url.toString();
    return;
  }

  QXmlStreamReader reader(reply);
  reader.readNextStartElement();

  if (reader.name() != "subsonic-response") {
    qLog(Warning) << "Not a subsonic-response. Aborting playlist fetch.";
    return;
  }

  if (reader.attributes().value("status") != "ok") {
    qLog(Warning) << "Status not okay. Aborting playlist fetch.";
    return;
  }

  // Read album information
  reader.readNextStartElement();
  if (reader.name() != "album") {
    qLog(Warning) << "album tag expected. Aborting playlist fetch.";
    return;
  }

  QString album_artist = reader.attributes().value("artist").toString();

  // Read song information
  while (reader.readNextStartElement()) {
    if (reader.name() != "song") {
      qLog(Warning) << "song tag expected. Aborting playlist fetch.";
      return;
    }

    Song song;
    QString id = reader.attributes().value("id").toString();
    song.set_title(reader.attributes().value("title").toString());
    song.set_album(reader.attributes().value("album").toString());
    song.set_track(reader.attributes().value("track").toString().toInt());
    song.set_disc(reader.attributes().value("discNumber").toString().toInt());
    song.set_artist(reader.attributes().value("artist").toString());
    song.set_albumartist(album_artist);
    song.set_bitrate(reader.attributes().value("bitRate").toString().toInt());
    song.set_year(reader.attributes().value("year").toString().toInt());
    song.set_genre(reader.attributes().value("genre").toString());
    qint64 length = reader.attributes().value("duration").toString().toInt();
    length *= kNsecPerSec;
    song.set_length_nanosec(length);
    QUrl url = QUrl(QString("subsonic://%1").arg(id));
    song.set_url(url);
    song.set_filesize(reader.attributes().value("size").toString().toInt());
    QFileInfo fi(reader.attributes().value("path").toString());
    song.set_basefilename(fi.fileName());
    // We need to set these to satisfy the database constraints
    song.set_directory_id(0);
    song.set_mtime(0);
    song.set_ctime(0);

    if (reader.attributes().hasAttribute("playCount")) {
      song.set_playcount(
          reader.attributes().value("playCount").toString().toInt());
    }

    list << std::shared_ptr<PlaylistItem>(
        new InternetPlaylistItem(service, song));

    reader.skipCurrentElement();
  }
}
开发者ID:ConfusedGiant,项目名称:Clementine,代码行数:83,代码来源:subsonicdynamicplaylist.cpp

示例14: performUpgrade

void FirmwareDownloader::performUpgrade()
{
    if (!m_updateAvailable) {
        qWarning() << "No update available";
        return;
    }

    if (m_upgradeInProgress) {
        qWarning() << "Upgrade already in progress. Won't start another one";
        return;
    }

    m_upgradeInProgress = true;
    emit upgradingChanged();

    QNetworkRequest request(m_url);
    QNetworkReply *reply = m_nam->get(request);
    connect(reply, &QNetworkReply::finished, [this, reply](){
        reply->deleteLater();

        if (reply->error() != QNetworkReply::NoError) {
            qWarning() << "Erorr fetching firmware" << reply->errorString();
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }

        QByteArray data = reply->readAll();

        QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Sha256).toHex();

        if (hash != m_hash) {
            qWarning() << "Downloaded data hash doesn't match hash from target";
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }

        QDir dir("/tmp/" + m_pebble->address().toString().replace(":", "_"));
        if (!dir.exists() && !dir.mkpath(dir.absolutePath())) {
            qWarning() << "Error saving file" << dir.absolutePath();
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }
        QString path = "/tmp/" + m_pebble->address().toString().replace(":", "_");
        QFile f(path + "/" + reply->request().url().fileName());
        if (!f.open(QFile::WriteOnly | QFile::Truncate)) {
            qWarning() << "Cannot open tmp file for writing" << f.fileName();
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }
        f.write(data);
        f.close();

        if (!ZipHelper::unpackArchive(f.fileName(), path)) {
            qWarning() << "Error unpacking firmware archive";
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }

        Bundle firmware(path);
        if (firmware.file(Bundle::FileTypeFirmware).isEmpty() || firmware.file(Bundle::FileTypeResources).isEmpty()) {
            qWarning() << "Firmware bundle file missing binary or resources";
            m_upgradeInProgress = false;
            emit upgradingChanged();
            return;
        }

        qDebug() << "** Starting firmware upgrade **";
        m_bundlePath = path;
        m_connection->systemMessage(WatchConnection::SystemMessageFirmwareStart);

    });
}
开发者ID:gitter-badger,项目名称:rockpool,代码行数:77,代码来源:firmwaredownloader.cpp

示例15: onRequestSessionRegister

//SLOTS
void QBNetwork::onRequestSessionRegister() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

	QString response;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			const int available = reply->bytesAvailable();
			if (available > 0) {
				const QByteArray buffer(reply->readAll());
				response = QString::fromUtf8(buffer);

				QFile sourceFile("app/native/assets/JDataSession.json");
				if (!sourceFile.open(QIODevice::WriteOnly))
					return;
				sourceFile.write(response.toAscii());

				JsonDataAccess jda;
				QVariant qtData = jda.loadFromBuffer(response);
				if (jda.hasError()) {
					const DataAccessError err = jda.error();
					showError(
							tr("Error converting JSON data: %1").arg(
									err.errorMessage()));
				} else {
					const QVariantMap object = qtData.value<QVariantMap>();
					QMapIterator<QString, QVariant> it(object);
					while (it.hasNext()) {
						it.next();
						if (it.key() == "session") {
							QVariantMap sessObject = it.value().toMap();
							QMapIterator<QString, QVariant> sit(sessObject);
							while (sit.hasNext()) {
								sit.next();
								if (sit.key() == "user_id") {
									m_userId = sit.value().toString();
								}
								if (sit.key() == "token") {
									m_token = sit.value().toString();
								}
							}
						}
					}
				}
			}
		} else {
			successLoad = true;
			emit loadingChanged();
			emit unauthorizedChanged();
			emit completeLogin();

			if (reply->error() < 100) {
				showError("Please check your internet connection");
				return;
			}

			if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "401") {
				showError("Incorrect login or password");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "422") {
				showError("Login has already been taken");
				return;
			} else if (reply->attribute(
					QNetworkRequest::HttpStatusCodeAttribute).toString()
					== "404") {
				showError("The requested resource could not be found");
				return;
			} else {
				//another error
				showError("QBlox Server Error = " + response);
				return;
			}
		}
		reply->deleteLater();
	}
	//successLoad = true;
	//emit loadingChanged();
	//emit unauthorizedChanged();
	//emit completeLogin();

	registrationNewUser();
}
开发者ID:QuickBlox,项目名称:quickblox-blackberry10-sdk,代码行数:85,代码来源:QBNetwork.cpp


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