本文整理汇总了C++中QUrl::host方法的典型用法代码示例。如果您正苦于以下问题:C++ QUrl::host方法的具体用法?C++ QUrl::host怎么用?C++ QUrl::host使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QUrl
的用法示例。
在下文中一共展示了QUrl::host方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: url
//.........这里部分代码省略.........
else if (head.indexOf("<packet>") != -1){
load.danmaku = Parse::parseComment(data, Utils::Niconico);
}
else if (head.indexOf("<i>") != -1){
load.danmaku = Parse::parseComment(data, Utils::Bilibili);
QString i = QRegularExpression("(?<=<chatid>)\\d+(?=</chatid>)").match(head).captured();
if (!i.isEmpty()){
load.source = "http://comment.%1/%2.xml";
load.source = load.source.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
}
}
else if (head.indexOf("<c>") != -1){
load.danmaku = Parse::parseComment(data, Utils::AcfunLocalizer);
}
if (load.delay != 0){
for (Comment &c : load.danmaku){
c.time += load.delay;
}
}
Danmaku::instance()->appendToPool(&load);
emit stateChanged(task.state = None);
dequeue();
break;
}
}
};
directProc->priority = -100;
directProc->regular = [this, directProc](QString &code){
if (code.startsWith("full?") || code.startsWith("hist?")){
code.clear();
return false;
}
QUrl u = QUrl::fromUserInput(code);
if (!u.host().isEmpty() && !u.path().isEmpty()){
return true;
}
if (QFileInfo(code).exists()){
return true;
}
code.clear();
return false;
};
auto fullBiProcess = [this](QNetworkReply *reply){
Q_D(Load);
Task &task = d->queue.head();
switch (task.state) {
case None:
{
emit progressChanged(0);
QString api("http://comment.%1/rolldate,%2");
api = api.arg(Utils::customUrl(Utils::Bilibili));
task.code = QUrlQuery(task.code.mid(5)).queryItemValue("source");
forward(QNetworkRequest(api.arg(QFileInfo(task.code).baseName())), Page);
break;
}
case Page:
{
QByteArray data = reply->readAll();
QJsonArray date = QJsonDocument::fromJson(data).array();
if (date.isEmpty()) {
emit stateChanged(203);
dequeue();
break;
}
QJsonObject head = date.first().toObject();
示例2: run
void IPTVStreamHandler::run(void)
{
RunProlog();
LOG(VB_GENERAL, LOG_INFO, LOC + "run()");
SetRunning(true, false, false);
// TODO Error handling..
// Setup
CetonRTSP *rtsp = NULL;
IPTVTuningData tuning = m_tuning;
if (m_tuning.GetURL(0).scheme().toLower() == "rtsp")
{
rtsp = new CetonRTSP(m_tuning.GetURL(0));
// Check RTSP capabilities
QStringList options;
if (!(rtsp->GetOptions(options) && options.contains("OPTIONS") &&
options.contains("DESCRIBE") && options.contains("SETUP") &&
options.contains("PLAY") && options.contains("TEARDOWN")))
{
LOG(VB_RECORD, LOG_ERR, LOC +
"RTSP interface did not support the necessary options");
delete rtsp;
SetRunning(false, false, false);
RunEpilog();
return;
}
if (!rtsp->Describe())
{
LOG(VB_RECORD, LOG_ERR, LOC +
"RTSP Describe command failed");
delete rtsp;
SetRunning(false, false, false);
RunEpilog();
return;
}
tuning = IPTVTuningData(
QString("rtp://%[email protected]%2:0")
.arg(m_tuning.GetURL(0).host())
.arg(QHostAddress(QHostAddress::Any).toString()), 0,
IPTVTuningData::kNone,
QString("rtp://%[email protected]%2:0")
.arg(m_tuning.GetURL(0).host())
.arg(QHostAddress(QHostAddress::Any).toString()), 0,
"", 0);
}
for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
{
QUrl url = tuning.GetURL(i);
if (url.port() < 0)
continue;
m_sockets[i] = new QTcpSocket();
m_sockets[i]->setSocketOption(QAbstractSocket::LowDelayOption, 1);
m_read_helpers[i] = new IPTVStreamHandlerReadHelper(
this, m_sockets[i], i);
if (!url.userInfo().isEmpty())
m_sender[i] = QHostAddress(url.userInfo());
m_sockets[i]->connectToHost(url.host().toAscii(), 3000);
if (m_sockets[i]->waitForConnected(1000))
{
m_sockets[i]->write("GET " + url.path().toAscii() + " HTTP/1.0\r\n\r\n\r\n\r\n");
m_sockets[i]->waitForBytesWritten(500);
}
else
{
qDebug("not Connected!");
m_sockets[i]->connectToHost(url.host().toAscii(), 3000);
m_sockets[i]->write("GET " + url.path().toAscii() + " HTTP/1.0\r\n\r\n\r\n\r\n");
m_sockets[i]->waitForBytesWritten(500);
}
}
//if (m_use_rtp_streaming)
// m_buffer = new RTPPacketBuffer(tuning.GetBitrate(0));
//else
m_buffer = new UDPPacketBuffer(tuning.GetBitrate(0));
m_write_helper = new IPTVStreamHandlerWriteHelper(this);
m_write_helper->Start();
bool error = false;
/*if (rtsp)
{
// Start Streaming
if (!rtsp->Setup(m_sockets[0]->localPort(),
m_sockets[1]->localPort()) ||
!rtsp->Play())
{
LOG(VB_RECORD, LOG_ERR, LOC +
//.........这里部分代码省略.........
示例3: fi
QNetworkReplyFileImpl::QNetworkReplyFileImpl(QObject *parent, const QNetworkRequest &req, const QNetworkAccessManager::Operation op)
: QNetworkReply(*new QNetworkReplyFileImplPrivate(), parent)
{
setRequest(req);
setUrl(req.url());
setOperation(op);
setFinished(true);
QNetworkReply::open(QIODevice::ReadOnly);
QNetworkReplyFileImplPrivate *d = (QNetworkReplyFileImplPrivate*) d_func();
QUrl url = req.url();
if (url.host() == QLatin1String("localhost"))
url.setHost(QString());
#if !defined(Q_OS_WIN)
// do not allow UNC paths on Unix
if (!url.host().isEmpty()) {
// we handle only local files
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Request for opening non-local file %1").arg(url.toString());
setError(QNetworkReply::ProtocolInvalidOperationError, msg);
QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ProtocolInvalidOperationError));
QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
return;
}
#endif
if (url.path().isEmpty())
url.setPath(QLatin1String("/"));
setUrl(url);
QString fileName = url.toLocalFile();
if (fileName.isEmpty()) {
if (url.scheme() == QLatin1String("qrc")) {
fileName = QLatin1Char(':') + url.path();
} else {
#if defined(Q_OS_ANDROID)
if (url.scheme() == QLatin1String("assets"))
fileName = QLatin1String("assets:") + url.path();
else
#endif
fileName = url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery);
}
}
QFileInfo fi(fileName);
if (fi.isDir()) {
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Cannot open %1: Path is a directory").arg(url.toString());
setError(QNetworkReply::ContentOperationNotPermittedError, msg);
QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ContentOperationNotPermittedError));
QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
return;
}
d->realFile.setFileName(fileName);
bool opened = d->realFile.open(QIODevice::ReadOnly | QIODevice::Unbuffered);
// could we open the file?
if (!opened) {
QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Error opening %1: %2")
.arg(d->realFile.fileName(), d->realFile.errorString());
if (d->realFile.exists()) {
setError(QNetworkReply::ContentAccessDenied, msg);
QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ContentAccessDenied));
} else {
setError(QNetworkReply::ContentNotFoundError, msg);
QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ContentNotFoundError));
}
QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
return;
}
setHeader(QNetworkRequest::LastModifiedHeader, fi.lastModified());
d->realFileSize = fi.size();
setHeader(QNetworkRequest::ContentLengthHeader, d->realFileSize);
QMetaObject::invokeMethod(this, "metaDataChanged", Qt::QueuedConnection);
QMetaObject::invokeMethod(this, "downloadProgress", Qt::QueuedConnection,
Q_ARG(qint64, d->realFileSize), Q_ARG(qint64, d->realFileSize));
QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection);
QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
}
示例4: dropMimeData
bool TreeWidget::dropMimeData(QTreeWidgetItem* parent, int,
const QMimeData* data, Qt::DropAction action)
{
if (action == Qt::IgnoreAction) {
return true;
}
if (parent && !parent->text(1).isEmpty()) { // parent is a bookmark, go one level up!
parent = parent->parent();
}
if (!parent) {
parent = invisibleRootItem();
}
bool ok = false;
if (data->hasUrls()) {
QString folder = (parent == invisibleRootItem()) ? QLatin1String("unsorted") : parent->text(0);
QUrl url = data->urls().at(0);
QString title = data->text().isEmpty() ? url.host() + url.path() : data->text();
emit linkWasDroped(url, title, data->imageData(), folder, &ok);
return ok;
}
if (!data->hasFormat(m_mimeType)) {
return false;
}
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
QByteArray ba = data->data(m_mimeType);
QDataStream stream(&ba, QIODevice::ReadOnly);
if (stream.atEnd()) {
return false;
}
QSqlDatabase db = QSqlDatabase::database();
db.transaction();
setUpdatesEnabled(false);
while (!stream.atEnd()) {
QTreeWidgetItem* item = new QTreeWidgetItem;
item->read(stream);
bool parentIsRoot = item->data(0, ITEM_IS_TOPLEVEL).toBool();
QString oldParentTitle = item->data(0, ITEM_PARENT_TITLE).toString();
bool isFolder = item->text(1).isEmpty();
if (isFolder && (item->text(0) == _bookmarksMenu ||
item->text(0) == _bookmarksToolbar)) {
continue;
}
bool parentIsOldParent = parentIsRoot ? (parent == invisibleRootItem()) : (oldParentTitle == parent->text(0));
if (parentIsOldParent || (isFolder && parent != invisibleRootItem() &&
parent->text(0) != _bookmarksToolbar)) {
// just 'Bookmarks In ToolBar' folder can have subfolders
continue;
}
if (isFolder) {
emit folderParentChanged(item->text(0), parent->text(0) == _bookmarksToolbar, &ok);
}
else {
emit bookmarkParentChanged(item->data(0, Qt::UserRole + 10).toInt(),
parent->text(0), oldParentTitle, &ok);
}
if (!ok) {
continue;
}
}
db.commit();
clearSelection();
setUpdatesEnabled(true);
QApplication::restoreOverrideCursor();
return true;
}
示例5: setValue
void SettingsManager::setValue(const QString &key, const QVariant &value, const QUrl &url)
{
if (!url.isEmpty())
{
if (value.isNull())
{
QSettings(m_overridePath, QSettings::IniFormat).remove((url.isLocalFile() ? QLatin1String("localhost") : url.host()) + QLatin1Char('/') + key);
}
else
{
QSettings(m_overridePath, QSettings::IniFormat).setValue((url.isLocalFile() ? QLatin1String("localhost") : url.host()) + QLatin1Char('/') + key, value);
}
return;
}
if (getValue(key) != value)
{
QSettings(m_globalPath, QSettings::IniFormat).setValue(key, value);
emit m_instance->valueChanged(key, value);
}
}
示例6: handleUserInput
void AddressWidget::handleUserInput(const QString &text)
{
BookmarksItem *bookmark = BookmarksManager::getBookmark(text);
if (bookmark)
{
WindowsManager *windowsManager = SessionsManager::getWindowsManager();
if (windowsManager)
{
windowsManager->open(bookmark);
return;
}
}
if (text == QString(QLatin1Char('~')) || text.startsWith(QLatin1Char('~') + QDir::separator()))
{
const QStringList locations = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if (!locations.isEmpty())
{
emit requestedLoadUrl(QUrl(locations.first() + text.mid(1)));
return;
}
}
if (QFileInfo(text).exists())
{
emit requestedLoadUrl(QUrl::fromLocalFile(QFileInfo(text).canonicalFilePath()));
return;
}
const QUrl url = QUrl::fromUserInput(text);
if (url.isValid() && (url.isLocalFile() || QRegularExpression(QLatin1String("^(\\w+\\:\\S+)|([\\w\\-]+\\.[a-zA-Z]{2,}(/\\S*)?$)")).match(text).hasMatch()))
{
emit requestedLoadUrl(url);
return;
}
const QString keyword = text.section(QLatin1Char(' '), 0, 0);
const QStringList engines = SearchesManager::getSearchEngines();
SearchInformation *engine = NULL;
for (int i = 0; i < engines.count(); ++i)
{
engine = SearchesManager::getSearchEngine(engines.at(i));
if (engine && keyword == engine->keyword)
{
emit requestedSearch(text.section(QLatin1Char(' '), 1), engine->identifier);
return;
}
}
const int lookupTimeout = SettingsManager::getValue(QLatin1String("AddressField/HostLookupTimeout")).toInt();
if (url.isValid() && lookupTimeout > 0)
{
if (text == m_lookupQuery)
{
return;
}
m_lookupQuery = text;
if (m_lookupTimer != 0)
{
QHostInfo::abortHostLookup(m_lookupIdentifier);
killTimer(m_lookupTimer);
m_lookupTimer = 0;
}
m_lookupIdentifier = QHostInfo::lookupHost(url.host(), this, SLOT(verifyLookup(QHostInfo)));
m_lookupTimer = startTimer(lookupTimeout);
return;
}
emit requestedSearch(text, SettingsManager::getValue(QLatin1String("Search/DefaultSearchEngine")).toString());
}
示例7: getValue
QVariant SettingsManager::getValue(const QString &key, const QUrl &url)
{
if (!url.isEmpty())
{
return QSettings(m_overridePath, QSettings::IniFormat).value((url.isLocalFile() ? QLatin1String("localhost") : url.host()) + QLatin1Char('/') + key, getValue(key));
}
return QSettings(m_globalPath, QSettings::IniFormat).value(key, getDefaultValue(key));
}
示例8: CacheChannelIcon
bool PixmapChannel::CacheChannelIcon(void)
{
if (icon.isEmpty())
return false;
m_localIcon = icon;
// Is icon local?
if (QFile(icon).exists())
return true;
QString localDirStr = QString("%1/channels").arg(GetConfDir());
QDir localDir(localDirStr);
if (!localDir.exists() && !localDir.mkdir(localDirStr))
{
VERBOSE(VB_IMPORTANT, QString("Icons directory is missing and could "
"not be created: %1").arg(localDirStr));
icon.clear();
return false;
}
// Has it been saved to the local cache?
m_localIcon = QString("%1/%2").arg(localDirStr)
.arg(QFileInfo(icon).fileName());
if (QFile(m_localIcon).exists())
return true;
// Get address of master backed
QString url = gCoreContext->GetMasterHostPrefix("ChannelIcons");
if (url.length() < 1)
{
icon.clear();
return false;
}
url.append(icon);
QUrl qurl = url;
if (qurl.host().isEmpty())
{
icon.clear();
return false;
}
RemoteFile *rf = new RemoteFile(url, false, false, 0);
QByteArray data;
bool ret = rf->SaveAs(data);
delete rf;
if (ret && data.size())
{
QImage image;
image.loadFromData(data);
//if (image.loadFromData(data) && image.width() > 0
if (image.save(m_localIcon))
{
VERBOSE(VB_GENERAL, QString("Caching channel icon %1").arg(m_localIcon));
return true;
}
else
VERBOSE(VB_GENERAL, QString("Failed to save to %1").arg(m_localIcon));
}
// if we get here then the icon is set in the db but couldn't be found
// anywhere so maybe we should remove it from the DB?
icon.clear();
return false;
}
示例9: reqUrl
QNetworkReply *AccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData)
{
const QUrl reqUrl(req.url());
if (!d->externalContentAllowed &&
!KDEPrivate::AccessManagerReply::isLocalRequest(reqUrl) &&
reqUrl.scheme() != QL1S("data")) {
//qDebug() << "Blocked: " << reqUrl;
return new KDEPrivate::AccessManagerReply(op, req, QNetworkReply::ContentAccessDenied, i18n("Blocked request."), this);
}
// Check if the internal ignore content disposition header is set.
const bool ignoreContentDisposition = req.hasRawHeader("x-kdewebkit-ignore-disposition");
// Retrieve the KIO meta data...
KIO::MetaData metaData;
d->setMetaDataForRequest(req, metaData);
KIO::SimpleJob *kioJob = 0;
switch (op) {
case HeadOperation: {
//qDebug() << "HeadOperation:" << reqUrl;
kioJob = KIO::mimetype(reqUrl, KIO::HideProgressInfo);
break;
}
case GetOperation: {
//qDebug() << "GetOperation:" << reqUrl;
if (!reqUrl.path().isEmpty() || reqUrl.host().isEmpty()) {
kioJob = KIO::storedGet(reqUrl, KIO::NoReload, KIO::HideProgressInfo);
} else {
kioJob = KIO::stat(reqUrl, KIO::HideProgressInfo);
}
// WORKAROUND: Avoid the brain damaged stuff QtWebKit does when a POST
// operation is redirected! See BR# 268694.
metaData.remove(QStringLiteral("content-type")); // Remove the content-type from a GET/HEAD request!
break;
}
case PutOperation: {
//qDebug() << "PutOperation:" << reqUrl;
if (outgoingData) {
Q_ASSERT(outgoingData->isReadable());
StoredTransferJob* storedJob = KIO::storedPut(outgoingData, reqUrl, -1, KIO::HideProgressInfo);
storedJob->setAsyncDataEnabled(outgoingData->isSequential());
QVariant len = req.header(QNetworkRequest::ContentLengthHeader);
if (len.isValid()) {
storedJob->setTotalSize(len.toInt());
}
kioJob = storedJob;
} else {
kioJob = KIO::put(reqUrl, -1, KIO::HideProgressInfo);
}
break;
}
case PostOperation: {
kioJob = KIO::storedHttpPost(outgoingData, reqUrl, sizeFromRequest(req), KIO::HideProgressInfo);
if (!metaData.contains(QStringLiteral("content-type"))) {
const QVariant header = req.header(QNetworkRequest::ContentTypeHeader);
if (header.isValid()) {
metaData.insert(QStringLiteral("content-type"),
(QStringLiteral("Content-Type: ") + header.toString()));
} else {
metaData.insert(QStringLiteral("content-type"),
QStringLiteral("Content-Type: application/x-www-form-urlencoded"));
}
}
break;
}
case DeleteOperation: {
//qDebug() << "DeleteOperation:" << reqUrl;
kioJob = KIO::http_delete(reqUrl, KIO::HideProgressInfo);
break;
}
case CustomOperation: {
const QByteArray &method = req.attribute(QNetworkRequest::CustomVerbAttribute).toByteArray();
//qDebug() << "CustomOperation:" << reqUrl << "method:" << method << "outgoing data:" << outgoingData;
if (method.isEmpty()) {
return new KDEPrivate::AccessManagerReply(op, req, QNetworkReply::ProtocolUnknownError, i18n("Unknown HTTP verb."), this);
}
const qint64 size = sizeFromRequest(req);
if (size > 0) {
kioJob = KIO::http_post(reqUrl, outgoingData, size, KIO::HideProgressInfo);
} else {
kioJob = KIO::get(reqUrl, KIO::NoReload, KIO::HideProgressInfo);
}
metaData.insert(QStringLiteral("CustomHTTPMethod"), method);
break;
}
default: {
qCWarning(KIO_WIDGETS) << "Unsupported KIO operation requested! Defering to QNetworkAccessManager...";
return QNetworkAccessManager::createRequest(op, req, outgoingData);
}
}
//.........这里部分代码省略.........
示例10: tryApplyJsonp
// return true if jsonp applied
bool tryApplyJsonp(const DomainMap::JsonpConfig &config, bool *ok, QString *errorMessage)
{
*ok = true;
// must be a GET
if(requestData.method != "GET")
return false;
QString callbackParam = QString::fromUtf8(config.callbackParam);
if(callbackParam.isEmpty())
callbackParam = "callback";
QString bodyParam;
if(!config.bodyParam.isEmpty())
bodyParam = QString::fromUtf8(config.bodyParam);
QUrl uri = requestData.uri;
QUrlQuery query(uri);
// two ways to activate JSON-P:
// 1) callback param present
// 2) default callback specified in configuration and body param present
if(!query.hasQueryItem(callbackParam) &&
(config.defaultCallback.isEmpty() || bodyParam.isEmpty() || !query.hasQueryItem(bodyParam)))
{
return false;
}
QByteArray callback;
if(query.hasQueryItem(callbackParam))
{
callback = parsePercentEncoding(query.queryItemValue(callbackParam, QUrl::FullyEncoded).toUtf8());
if(callback.isEmpty())
{
log_debug("requestsession: id=%s invalid callback parameter, rejecting", rid.second.data());
*ok = false;
*errorMessage = "Invalid callback parameter.";
return false;
}
query.removeAllQueryItems(callbackParam);
}
else
callback = config.defaultCallback;
QString method;
if(query.hasQueryItem("_method"))
{
method = QString::fromLatin1(parsePercentEncoding(query.queryItemValue("_method", QUrl::FullyEncoded).toUtf8()));
if(!validMethod(method))
{
log_debug("requestsession: id=%s invalid _method parameter, rejecting", rid.second.data());
*ok = false;
*errorMessage = "Invalid _method parameter.";
return false;
}
query.removeAllQueryItems("_method");
}
HttpHeaders headers;
if(query.hasQueryItem("_headers"))
{
QJsonParseError e;
QJsonDocument doc = QJsonDocument::fromJson(parsePercentEncoding(query.queryItemValue("_headers", QUrl::FullyEncoded).toUtf8()), &e);
if(e.error != QJsonParseError::NoError || !doc.isObject())
{
log_debug("requestsession: id=%s invalid _headers parameter, rejecting", rid.second.data());
*ok = false;
*errorMessage = "Invalid _headers parameter.";
return false;
}
QVariantMap headersMap = doc.object().toVariantMap();
QMapIterator<QString, QVariant> vit(headersMap);
while(vit.hasNext())
{
vit.next();
if(vit.value().type() != QVariant::String)
{
log_debug("requestsession: id=%s invalid _headers parameter, rejecting", rid.second.data());
*ok = false;
*errorMessage = "Invalid _headers parameter.";
return false;
}
QByteArray key = vit.key().toUtf8();
// ignore some headers that we explicitly set later on
if(qstricmp(key.data(), "host") == 0)
continue;
if(qstricmp(key.data(), "accept") == 0)
continue;
headers += HttpHeader(key, vit.value().toString().toUtf8());
}
//.........这里部分代码省略.........
示例11: postHttp
/**
* \brief Static function for performing a http post request to a url.
*
* This is a synchronous function, it will block according to the vars.
*/
QString HttpComms::postHttp(
QUrl &url,
QHttpRequestHeader *pAddlHdr, QIODevice *pData,
int timeoutMS, int maxRetries,
int maxRedirects, bool allowGzip,
Credentials *webCred, bool isInQtEventThread,
QString userAgent)
{
int redirectCount = 0;
int timeoutCount = 0;
QString res;
HttpComms *httpGrabber = NULL;
QString hostname;
QHttpRequestHeader header("POST", url.path() + url.encodedQuery());
// Add main header values
header.setValue("Host", url.host());
if (userAgent.toLower() == "<default>")
{
userAgent = "Mozilla/9.876 (X11; U; Linux 2.2.12-20 i686, en) "
"Gecko/25250101 Netscape/5.432b1";
}
if (!userAgent.isEmpty())
header.setValue("User-Agent", userAgent);
if (allowGzip)
header.setValue( "Accept-Encoding", "gzip");
// Merge any Additional Headers passed by caller.
if (pAddlHdr)
{
QList< QPair< QString, QString > > values = pAddlHdr->values();
for (QList< QPair< QString, QString > >::iterator it = values.begin();
it != values.end();
++it )
{
header.setValue( (*it).first, (*it).second );
}
}
while (1)
{
if (hostname.isEmpty())
hostname = url.host(); // hold onto original host
if (url.host().isEmpty()) // can occur on redirects to partial paths
url.setHost(hostname);
VERBOSE(VB_NETWORK, QString("postHttp: grabbing: %1").arg(url.toString()));
delete httpGrabber;
httpGrabber = new HttpComms;
if (webCred)
httpGrabber->setCredentials(*webCred, CRED_WEB);
httpGrabber->request(url, header, timeoutMS, pData );
while (!httpGrabber->isDone())
{
if (isInQtEventThread)
qApp->processEvents();
usleep(10000);
}
// Handle timeout
if (httpGrabber->isTimedout())
{
VERBOSE(VB_NETWORK, QString("timeout for url: %1").arg(url.toString()));
// Increment the counter and check we're not over the limit
if (timeoutCount++ >= maxRetries)
{
VERBOSE(VB_IMPORTANT, QString("Failed to contact server for url: %1").arg(url.toString()));
break;
}
// Try again
VERBOSE(VB_NETWORK, QString("Attempt # %1/%2 for url: %3")
.arg(timeoutCount + 1)
.arg(maxRetries)
.arg(url.toString()));
continue;
}
// Check for redirection
if (!httpGrabber->getRedirectedURL().isEmpty())
{
VERBOSE(VB_NETWORK, QString("Redirection: %1, count: %2, max: %3")
.arg(httpGrabber->getRedirectedURL())
//.........这里部分代码省略.........
示例12: SendSubscribeRequest
int UPNPSubscription::SendSubscribeRequest(const QString &callback,
const QString &usn,
const QUrl &url,
const QString &path,
const QString &uuidin,
QString &uuidout)
{
QString host = url.host();
int port = url.port();
QByteArray sub;
QTextStream data(&sub);
data.setCodec(QTextCodec::codecForName("UTF-8"));
// N.B. Play On needs an extra space between SUBSCRIBE and path...
data << QString("SUBSCRIBE %1 HTTP/1.1\r\n").arg(path);
data << QString("HOST: %1:%2\r\n").arg(host).arg(QString::number(port));
if (uuidin.isEmpty()) // new subscription
{
data << QString("CALLBACK: <%1%2>\r\n")
.arg(callback).arg(usn);
data << "NT: upnp:event\r\n";
}
else // renewal
data << QString("SID: uuid:%1\r\n").arg(uuidin);
data << QString("TIMEOUT: Second-%1\r\n").arg(SUBSCRIPTION_TIME);
data << "\r\n";
data.flush();
LOG(VB_UPNP, LOG_DEBUG, LOC + "\n\n" + sub);
MSocketDevice *sockdev = new MSocketDevice(MSocketDevice::Stream);
BufferedSocketDevice *sock = new BufferedSocketDevice(sockdev);
sockdev->setBlocking(true);
QString uuid;
QString timeout;
uint result = 0;
if (sock->Connect(QHostAddress(host), port))
{
if (sock->WriteBlockDirect(sub.constData(), sub.size()) != -1)
{
bool ok = false;
QString line = sock->ReadLine(MAX_WAIT);
while (!line.isEmpty())
{
LOG(VB_UPNP, LOG_DEBUG, LOC + line);
if (line.contains("HTTP/1.1 200 OK", Qt::CaseInsensitive))
ok = true;
if (line.startsWith("SID:", Qt::CaseInsensitive))
uuid = line.mid(4).trimmed().mid(5).trimmed();
if (line.startsWith("TIMEOUT:", Qt::CaseInsensitive))
timeout = line.mid(8).trimmed().mid(7).trimmed();
if (ok && !uuid.isEmpty() && !timeout.isEmpty())
break;
line = sock->ReadLine(MAX_WAIT);
}
if (ok && !uuid.isEmpty() && !timeout.isEmpty())
{
uuidout = uuid;
result = timeout.toUInt();
}
else
{
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("Failed to subscribe to %1").arg(usn));
}
}
else
{
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("Socket write error for %1:%2") .arg(host).arg(port));
}
sock->Close();
}
else
{
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("Failed to open socket for %1:%2") .arg(host).arg(port));
}
delete sock;
delete sockdev;
return result;
}
示例13: acceptNavigationRequest
bool WebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type, const QByteArray& postData)
{
QString scheme = request.url().scheme();
if (scheme == QLatin1String("mailto")
|| scheme == QLatin1String("ftp")) {
// QDesktopServices::openUrl(request.url());
return false;
}
if (IS_CRAWLER) // when crawler, we run the webapplication is the same process
// make it easier for replay
return QWebPage::acceptNavigationRequest(frame, request, type, postData);
WebView::OpenType t = WebView::NewWebApp;
WebView* view = qobject_cast<WebView*>(parent());
Q_ASSERT(view != 0);
// little trick to avoid double post
if (m_posted) {
m_posted = false;
} else if (postData.size() > 0) {
m_posted = true;
}
// ctrl open in new tab
// ctrl-shift open in new tab and select
// ctrl-alt open in new window
if (type == QWebPage::NavigationTypeLinkClicked
&& (m_keyboardModifiers & Qt::ControlModifier
|| m_pressedButtons == Qt::MidButton)) {
bool newWindow = (m_keyboardModifiers & Qt::AltModifier);
if (newWindow) {
t = WebView::NewWindow;
} else {
bool selectNewTab = (m_keyboardModifiers & Qt::ShiftModifier);
if (selectNewTab)
t = WebView::NewTabSelect;
else
t = WebView::NewTabNoSelect;
}
// check and load
view->loadPolicy(request, postData, t);
m_keyboardModifiers = Qt::NoModifier;
m_pressedButtons = Qt::NoButton;
return false;
}
//qDebug() << "navigation request url: " << request.url();
QUrl::FormattingOptions format = QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::StripTrailingSlash;
if (frame == mainFrame()) {
//qDebug() << "mainFrame navigation request to " << request.url();
m_loadingUrl = request.url();
QUrl current = view->url();
bool sop = (m_loadingUrl.scheme().toLower() == current.scheme().toLower())
&& (m_loadingUrl.host().toLower() == current.host().toLower())
&& (m_loadingUrl.port() == current.port());
//QUrl::FormattingOptions format = QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::StripTrailingSlash;
if (!sop //(view->loaded() || type == QWebPage::NavigationTypeLinkClicked) && !sop
/*(m_loadingUrl.toString(format) != current.toString(format)) */) {
t = WebView::NewWebApp;
// check and load
if (m_posted)
view->loadPolicy(request, postData, t);
else
view->loadPolicy(request, QByteArray(), t);
return false;
} else {
emit loadingUrl(m_loadingUrl);
if ((type != NavigationTypeOther) && (type != NavigationTypeReload) && (type != NavigationTypeBackOrForward)
|| (view->m_userAction)) {
QVariant var(m_loadingUrl.toString());
OPNET::OpNetwork::instance()->sendUIMsg(MSG_addHistoryItem, getByteArray(var));
view->m_userAction = false;
}
if (type == NavigationTypeBackOrForward) {
//QVariant var(m_back);
//OPNET::OpNetwork::instance()->sendUIMsg(MSG_navBackOrForward, getByteArray(var));
m_back = false;
}
}
}
else if(frame == 0)
{
t = WebView::NewTabNoSelect;
// check and load
view->loadPolicy(request, postData, t);
return false;
}
// same-origin and "about:blank" navigation requests fall-through to acceptNavigationRequest
else if( m_iframeHandled &&
(request.url().toString(format | QUrl::RemovePath) != view->url().toString(format | QUrl::RemovePath)
&& request.url().toString() != "about:blank")) {
//.........这里部分代码省略.........
示例14: query
ServerItem *ServerItem::fromMimeData(const QMimeData *mime, QWidget *p) {
if (mime->hasFormat(QLatin1String("OriginatedInMumble")))
return NULL;
QUrl url;
#if QT_VERSION >= 0x050000
QUrlQuery query(url);
#endif
if (mime->hasUrls() && ! mime->urls().isEmpty())
url = mime->urls().at(0);
else if (mime->hasText())
url = QUrl::fromEncoded(mime->text().toUtf8());
QString qsFile = url.toLocalFile();
if (! qsFile.isEmpty()) {
QFile f(qsFile);
// Make sure we don't accidently read something big the user
// happened to have in his clipboard. We only want to look
// at small link files.
if (f.open(QIODevice::ReadOnly) && f.size() < 10240) {
QByteArray qba = f.readAll();
f.close();
url = QUrl::fromEncoded(qba, QUrl::StrictMode);
if (! url.isValid()) {
QSettings qs(qsFile, QSettings::IniFormat);
url = QUrl::fromEncoded(qs.value(QLatin1String("InternetShortcut/URL")).toByteArray(), QUrl::StrictMode);
}
}
}
if (! url.isValid() || (url.scheme() != QLatin1String("mumble")))
return NULL;
if (url.userName().isEmpty()) {
if (g.s.qsUsername.isEmpty()) {
bool ok;
QString defUserName = QInputDialog::getText(p, ConnectDialog::tr("Adding host %1").arg(url.host()), ConnectDialog::tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed();
if (! ok)
return NULL;
if (defUserName.isEmpty())
return NULL;
g.s.qsUsername = defUserName;
}
url.setUserName(g.s.qsUsername);
}
#if QT_VERSION >= 0x050000
if (! query.hasQueryItem(QLatin1String("title")))
query.addQueryItem(QLatin1String("title"), url.host());
ServerItem *si = new ServerItem(query.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password());
if (query.hasQueryItem(QLatin1String("url")))
si->qsUrl = query.queryItemValue(QLatin1String("url"));
#else
if (! url.hasQueryItem(QLatin1String("title")))
url.addQueryItem(QLatin1String("title"), url.host());
ServerItem *si = new ServerItem(url.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password());
if (url.hasQueryItem(QLatin1String("url")))
si->qsUrl = url.queryItemValue(QLatin1String("url"));
#endif
return si;
}
示例15: checkUrl
//! [2]
bool checkUrl(const QUrl &url) {
if (!url.isValid()) {
qDebug(QString("Invalid URL: %1").arg(url.toString()));
return false;
}
return true;
}
//! [2]
//! [3]
QFtp ftp;
ftp.connectToHost(url.host(), url.port(21));
//! [3]
//! [4]
http://www.example.com/cgi-bin/drawgraph.cgi?type-pie/color-green
//! [4]
//! [5]
QUrl baseUrl("http://qt.nokia.com/support");
QUrl relativeUrl("../products/solutions");
qDebug(baseUrl.resolved(relativeUrl).toString());
// prints "http://qt.nokia.com/products/solutions"
//! [5]