本文整理汇总了C++中QNetworkRequest类的典型用法代码示例。如果您正苦于以下问题:C++ QNetworkRequest类的具体用法?C++ QNetworkRequest怎么用?C++ QNetworkRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QNetworkRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: onDownloadRequested
void BrowserView::onDownloadRequested(const QNetworkRequest & request)
{
Dialog::DownloadDialog dlg (request.url(),this);
dlg.exec();
}
示例2: download
void DownloadManager::download(const QNetworkRequest &request, bool requestFileName)
{
if (request.url().isEmpty())
return;
handleUnsupportedContent(m_manager->get(request), requestFileName);
}
示例3: assert
void
TrainingstagebuchUploader::requestUpload()
{
assert(sessionId.length() > 0 );
parent->progressLabel->setText(tr("preparing Trainingstagebuch.org data ..."));
QHttpMultiPart *body = new QHttpMultiPart( QHttpMultiPart::FormDataType );
QHttpPart textPart;
textPart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"upload_submit\""));
textPart.setBody("hrm");
body->append( textPart );
QString fname = context->athlete->home->temp().absoluteFilePath(".ttbupload.pwx" );
QFile *uploadFile = new QFile( fname );
uploadFile->setParent(body);
PwxFileReader reader;
reader.writeRideFile(context, ride->ride(), *uploadFile );
parent->progressBar->setValue(parent->progressBar->value()+20/parent->shareSiteCount);
int limit = proMember
? 8 * 1024 * 1024
: 4 * 1024 * 1024;
if( uploadFile->size() >= limit ){
parent->errorLabel->setText(tr("temporary file too large for upload: %1 > %1 bytes")
.arg(uploadFile->size())
.arg(limit) );
eventLoop.quit();
return;
}
QHttpPart filePart;
filePart.setHeader(QNetworkRequest::ContentTypeHeader,
QVariant("application/octet-stream"));
filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"file\"; filename=\"gc-upload-ttb.pwx\""));
uploadFile->open(QIODevice::ReadOnly);
filePart.setBodyDevice(uploadFile);
body->append( filePart );
parent->progressLabel->setText(tr("sending to Trainingstagebuch.org ..."));
currentRequest = reqUpload;
#if QT_VERSION > 0x050000
QUrlQuery urlquery;
#else
QUrl urlquery( TTB_URL + "/file/upload" );
#endif
urlquery.addQueryItem( "view", "xml" );
urlquery.addQueryItem( "sso", sessionId );
#if QT_VERSION > 0x050000
QUrl url (TTB_URL + "/file/upload");
url.setQuery(urlquery.query());
QNetworkRequest request = QNetworkRequest(url);
#else
QNetworkRequest request = QNetworkRequest(urlquery);
#endif
request.setRawHeader( "Accept-Encoding", "identity" );
request.setRawHeader( "Accept", "application/xml" );
request.setRawHeader( "Accept-Charset", "utf-8" );
QNetworkReply *reply = networkMgr.post( request, body );
body->setParent( reply );
}
示例4: QDate
void
RideWithGpsUploader::requestUploadRideWithGPS()
{
parent->progressLabel->setText(tr("Upload ride..."));
parent->progressBar->setValue(parent->progressBar->value()+10/parent->shareSiteCount);
QEventLoop eventLoop;
QNetworkAccessManager networkMgr;
int prevSecs = 0;
long diffSecs = 0;
int year = ride->fileName.left(4).toInt();
int month = ride->fileName.mid(5,2).toInt();
int day = ride->fileName.mid(8,2).toInt();
int hour = ride->fileName.mid(11,2).toInt();
int minute = ride->fileName.mid(14,2).toInt();;
int second = ride->fileName.mid(17,2).toInt();;
QDate rideDate = QDate(year, month, day);
QTime rideTime = QTime(hour, minute, second);
QDateTime rideDateTime = QDateTime(rideDate, rideTime);
connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestUploadRideWithGPSFinished(QNetworkReply*)));
connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));
QString out, data;
QVector<RideFilePoint*> vectorPoints = ride->ride()->dataPoints();
int totalSize = vectorPoints.size();
int size = 0;
QString username = appsettings->cvalue(context->athlete->cyclist, GC_RWGPSUSER).toString();
QString password = appsettings->cvalue(context->athlete->cyclist, GC_RWGPSPASS).toString();
// application/json
out += "{\"apikey\": \"p24n3a9e\", ";
out += "\"email\": \""+username+"\", ";
out += "\"password\": \""+password+"\", ";
out += "\"track_points\": \"";
data += "\[";
foreach (const RideFilePoint *point, ride->ride()->dataPoints())
{
size++;
if (point->secs == 0.0)
continue;
diffSecs = point->secs - prevSecs;
prevSecs = point->secs;
rideDateTime = rideDateTime.addSecs(diffSecs);
data += "{\"x\": ";
data += QString("%1").arg(point->lon,0,'f',GPS_COORD_TO_STRING);
data += ", \"y\": ";
data += QString("%1").arg(point->lat,0,'f',GPS_COORD_TO_STRING);
data += ", \"t\": ";
data += QString("%1").arg(rideDateTime.toTime_t());
if (parent->altitudeChk->isChecked()) {
data += ", \"e\": ";
data += QString("%1").arg(point->alt);
}
if (parent->powerChk->isChecked()) {
data += ", \"p\": ";
data += QString("%1").arg(point->watts);
}
if (parent->cadenceChk->isChecked()) {
data += ", \"c\": ";
data += QString("%1").arg(point->cad);
}
if (parent->heartrateChk->isChecked()) {
data += ", \"h\": ";
data += QString("%1").arg(point->hr);
}
data += "}";
if(size < totalSize)
data += ",";
}
data += "]";
out += data.replace("\"","\\\"");
out += "\"}";
QUrl url = QUrl("http://ridewithgps.com/trips.json");
QNetworkRequest request = QNetworkRequest(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
parent->progressBar->setValue(parent->progressBar->value()+30/parent->shareSiteCount);
parent->progressLabel->setText(tr("Upload ride... Sending to RideWithGPS"));
networkMgr.post( request, out.toLatin1());
eventLoop.exec();
}
示例5: QFile
QScriptValue Web::download(const QString &urlString, const QScriptValue &options)
{
mData.clear();
if(mFileValue.isValid())
{
if(Code::File *file = qobject_cast<Code::File*>(mFileValue.toQObject()))
mFile = file->file();
else
mFile = new QFile(mFileValue.toString(), this);
mCloseFile = false;
if(!mFile->isOpen())
{
if(!mFile->open(QIODevice::WriteOnly))
{
throwError("OpenFileError", tr("Unable to open the destination file"));
return thisObject();
}
mCloseFile = true;
}
}
QUrl url(urlString);
if(url.scheme() == QString())
url = QUrl("http://" + urlString, QUrl::TolerantMode);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
QUrlQuery urlQuery;
#endif
QNetworkRequest request;
QScriptValueIterator it(options);
Method method = Get;
QByteArray postData;
while(it.hasNext())
{
it.next();
if(it.name() == "rawHeaders")
{
QScriptValueIterator headerIt(it.value());
while(headerIt.hasNext())
{
headerIt.next();
request.setRawHeader(headerIt.name().toUtf8(), headerIt.value().toString().toUtf8());
}
}
else if(it.name() == "method")
{
method = static_cast<Method>(it.value().toInt32());
}
else if(it.name() == "postData")
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
QScriptValueIterator postDataIt(it.value());
QUrlQuery postDataParameters;
while(postDataIt.hasNext())
{
postDataIt.next();
postDataParameters.addQueryItem(postDataIt.name(), postDataIt.value().toString());
}
postData = postDataParameters.toString(QUrl::FullyEncoded).toLatin1();
#else
QScriptValueIterator postDataIt(it.value());
QUrl postDataParameters;
while(postDataIt.hasNext())
{
postDataIt.next();
postDataParameters.addQueryItem(postDataIt.name(), postDataIt.value().toString());
}
postData = postDataParameters.encodedQuery();
#endif
}
else if(it.name() == "query")
{
QScriptValueIterator queryIt(it.value());
while(queryIt.hasNext())
{
queryIt.next();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
urlQuery.addQueryItem(queryIt.name(), queryIt.value().toString());
#else
url.addQueryItem(queryIt.name(), queryIt.value().toString());
#endif
}
//.........这里部分代码省略.........
示例6: acceptNavigationRequest
bool HototWebPage::acceptNavigationRequest(QWebFrame * frame, const QNetworkRequest & request, NavigationType type)
{
Q_UNUSED(frame);
Q_UNUSED(type);
return handleUri(request.url().toString());
}
示例7: baseUrl
bool NewAccountPage::validatePage()
{
if(hasCreatedAccount)
{
return true;
}
serverQueryFinished = false;
serverQueryError = false;
//Check if passwords match
if(input_password->text() != input_confirmPassword->text())
{
label_message->setText(tr("<font color='red'>Passwords do not match</font>"));
return false;
}
label_message->setText("Creating account...");
QUrl baseUrl( "https://api.screencloud.net/1.0/users/register.xml" );
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
QUrlQuery query(baseUrl);
#else
QUrl query(baseUrl);
#endif
query.addQueryItem("oauth_version", "1.0");
query.addQueryItem("oauth_signature_method", "PLAINTEXT");
query.addQueryItem("oauth_consumer_key", CONSUMER_KEY_SCREENCLOUD);
query.addQueryItem("oauth_signature", CONSUMER_SECRET_SCREENCLOUD);
query.addQueryItem("oauth_timestamp", QString::number(QDateTime::currentDateTimeUtc().toTime_t()));
query.addQueryItem("oauth_nonce", NetworkUtils::generateNonce(15));
// create a request parameters map
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
QUrlQuery bodyParams;
#else
QUrl bodyParams;
#endif
bodyParams.addQueryItem("data[User][email]", input_email->text());
bodyParams.addQueryItem("data[User][password]", input_password->text());
bodyParams.addQueryItem("data[User][password_confirmation]", input_confirmPassword->text());
// construct the body string
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
QByteArray body = bodyParams.query(QUrl::FullyEncoded).toUtf8();
#else
QByteArray body = bodyParams.encodedQuery();
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
QUrl fullUrl(baseUrl);
fullUrl.setQuery(query);
#else
QUrl fullUrl(query);
#endif
QNetworkRequest request;
request.setUrl(fullUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
manager->post(request, body);
while (!serverQueryFinished) {
qApp->processEvents(QEventLoop::WaitForMoreEvents);
}
if(serverQueryError)
{
return false;
}
hasCreatedAccount = true;
return true;
}
示例8: fetchNotes
/**
* @brief ServerCommunicator::fetchNotes
*/
void ServerCommunicator::fetchNotes() {
QNetworkRequest request;
request.setUrl(QUrl("http://sync.silicanote.eu/silicanote-webapp/services/notes/getnotes"));
manager->get(request);
}
示例9: main
int main(int argc, char **argv)
{
QCoreApplication application(argc, argv);
application.setOrganizationName("CutePaste");
application.setApplicationName("CutePaste Desktop Console Frontend");
QTextStream standardOutputStream(stdout);
QFile dataFile;
QString firstArgument = QCoreApplication::arguments().size() < 2 ? QString() : QCoreApplication::arguments().at(1);
if (!firstArgument.isEmpty()) {
dataFile.setFileName(firstArgument);
dataFile.open(QIODevice::ReadOnly);
} else {
dataFile.open(stdin, QIODevice::ReadOnly);
}
QByteArray pasteTextByteArray = dataFile.readAll();
QJsonObject requestJsonObject;
requestJsonObject.insert(QStringLiteral("data"), QString::fromUtf8(pasteTextByteArray));
requestJsonObject.insert(QStringLiteral("language"), QStringLiteral("text"));
QJsonDocument requestJsonDocument(requestJsonObject);
QString baseUrlString = QStringLiteral("http://pastebin.kde.org");
QNetworkRequest networkRequest;
networkRequest.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);
networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
networkRequest.setUrl(QUrl(baseUrlString + "/api/json/create"));
QNetworkAccessManager networkAccessManager;
QScopedPointer<QNetworkReply> networkReplyScopedPointer(networkAccessManager.post(networkRequest, requestJsonDocument.toJson()));
QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::finished, [&]() {
QJsonParseError jsonParseError;
QByteArray replyJsonByteArray = networkReplyScopedPointer->readAll();
QJsonDocument replyJsonDocument = QJsonDocument::fromJson(replyJsonByteArray, &jsonParseError);
if (jsonParseError.error != QJsonParseError::NoError) {
qDebug() << "The json network reply is not valid json:" << jsonParseError.errorString();
QCoreApplication::quit();
}
if (!replyJsonDocument.isObject()) {
qDebug() << "The json network reply is not an object";
QCoreApplication::quit();
}
QJsonObject replyJsonObject = replyJsonDocument.object();
QJsonValue resultValue = replyJsonObject.value(QStringLiteral("result"));
if (!resultValue.isObject()) {
qDebug() << "The json network reply does not contain an object for the \"result\" key";
QCoreApplication::quit();
}
QJsonValue identifierValue = resultValue.toObject().value(QStringLiteral("id"));
if (!identifierValue.isString()) {
qDebug() << "The json network reply does not contain a string for the \"id\" key";
QCoreApplication::quit();
}
endl(standardOutputStream << baseUrlString << '/' << identifierValue.toString());
QCoreApplication::quit();
});
QObject::connect(networkReplyScopedPointer.data(), static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [&](QNetworkReply::NetworkError networkReplyError) {
if (networkReplyError != QNetworkReply::NoError)
endl(standardOutputStream << networkReplyScopedPointer->errorString());
});
QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::sslErrors, [&](QList<QSslError> networkReplySslErrors) {
if (!networkReplySslErrors.isEmpty()) {
foreach (const QSslError &networkReplySslError, networkReplySslErrors)
endl(standardOutputStream << networkReplySslError.errorString());
}
});
示例10: QVariant
QVariant LxHttp::httpRequest(QVariant varMethod, QVariant varUrl , QVariant varPostData)//, QScriptEngine *interpreter
{
enum LxHttpMethod
{
GET,
POST
};
QString url = "";
QString data ="";
LxHttpMethod method = GET;
if (varMethod.isNull() || varUrl.isNull())
{
return QVariant(0);
}
QString arg = varMethod.toString().trimmed().toUpper();
method = (arg == "POST") ? POST : GET;
url = varUrl.toString().trimmed();
if (0 != url.toLower().indexOf("http://"))
{
return QVariant("URIError: URL is not http://");
}
data = varPostData.toString();
QNetworkReply* reply;
QNetworkRequest req;
QNetworkAccessManager* manager = new QNetworkAccessManager();
if (method == POST)
{
// post 数据编码
req.setUrl(QUrl(url));
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
reply = manager->post(req, QUrl(data).toEncoded());
} else
{
if (data != "")
{
if (url.indexOf("?") != -1)
{
if (url.lastIndexOf("&") == url.size() - 1)
{
url = url + data;
}
else
{
url = url + "&" + data;
}
}
else
{
url= url + "?" + data;
}
}
reply = manager->get(QNetworkRequest(QUrl(url)));
}
// 开启局部事件循环
QEventLoop eventLoop;
connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
eventLoop.exec();
QByteArray responseData;
responseData = reply->readAll();
QString charset = QString(reply->rawHeader("Content-Type")).toLower();
QRegExp charsetRegExp("charset=([\\w-]+)\\b");
int pos = charset.indexOf(charsetRegExp);
if (pos > 0)
{
if (charsetRegExp.cap().size() < 2)
{
charset = "";
}
else
{
charset = charsetRegExp.cap(1);
}
}
else
{
charset = "";
}
QTextStream stream(responseData);
stream.setCodec(QTextCodec::codecForName(QByteArray("utf-8")));//charset.toLocal8Bit()
return QVariant(QString(stream.readAll()));
}
示例11: qDebug
void HttpAgent::debugResponse(QNetworkReply *reply)
{
//qDebug() << "HttpAgent::debugResponse()";
if ( !reply )
{
qDebug() << "HTTP Response: null!!";
}
qDebug() << __FUNCTION__ << ":reply from cache?="
<< reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool()
<< ":" << reply->url();
QNetworkRequest req = reply->request();
qDebug() << "HTTP Request: " << req.url();
wpp::qt::System &system = wpp::qt::System::getInstance();
if (reply->error() != QNetworkReply::NoError)
{
QNetworkReply::NetworkError error = reply->error();
QString errStr("Unknown");
switch ( error )
{
case QNetworkReply::ConnectionRefusedError:
errStr = "the remote server refused the connection (the server is not accepting requests)";
break;
case QNetworkReply::RemoteHostClosedError:
errStr = "the remote server closed the connection prematurely, before the entire reply was received and processed";
break;
case QNetworkReply::HostNotFoundError:
errStr = "the remote host name was not found (invalid hostname)";
system.setHasNetwork(false);
qDebug() << "system.setHasNetwork(false)";
break;
case QNetworkReply::TimeoutError:
errStr = "the connection to the remote server timed out";
break;
case QNetworkReply::OperationCanceledError:
errStr = "the operation was canceled via calls to abort() or close() before it was finished.";
break;
case QNetworkReply::SslHandshakeFailedError:
errStr = "the SSL/TLS handshake failed and the encrypted channel could not be established. The sslErrors() signal should have been emitted.";
break;
case QNetworkReply::TemporaryNetworkFailureError:
errStr = "the connection was broken due to disconnection from the network, however the system has initiated roaming to another access point. The request should be resubmitted and will be processed as soon as the connection is re-established.";
break;
case QNetworkReply::NetworkSessionFailedError:
errStr = "the connection was broken due to disconnection from the network or failure to start the network.";
break;
case QNetworkReply::BackgroundRequestNotAllowedError:
errStr = "the background request is not currently allowed due to platform policy.";
break;
case QNetworkReply::ProxyConnectionRefusedError:
errStr = "the connection to the proxy server was refused (the proxy server is not accepting requests)";
break;
case QNetworkReply::ProxyConnectionClosedError:
errStr = "the proxy server closed the connection prematurely, before the entire reply was received and processed";
break;
case QNetworkReply::ProxyNotFoundError:
errStr = "the proxy host name was not found (invalid proxy hostname)";
break;
case QNetworkReply::ProxyTimeoutError:
errStr = "the connection to the proxy timed out or the proxy did not reply in time to the request sent";
break;
case QNetworkReply::ProxyAuthenticationRequiredError:
errStr = "the proxy requires authentication in order to honour the request but did not accept any credentials offered (if any)";
break;
case QNetworkReply::ContentAccessDenied:
errStr = "the access to the remote content was denied (similar to HTTP error 401)";
break;
case QNetworkReply::ContentOperationNotPermittedError:
errStr = "the operation requested on the remote content is not permitted";
break;
case QNetworkReply::ContentNotFoundError:
errStr = "the remote content was not found at the server (similar to HTTP error 404)";
break;
case QNetworkReply::AuthenticationRequiredError:
errStr = "the remote server requires authentication to serve the content but the credentials provided were not accepted (if any)";
break;
case QNetworkReply::ContentReSendError:
errStr = "the request needed to be sent again, but this failed for example because the upload data could not be read a second time.";
break;
case QNetworkReply::ProtocolUnknownError:
errStr = "the Network Access API cannot honor the request because the protocol is not known";
break;
case QNetworkReply::ProtocolInvalidOperationError:
errStr = "the requested operation is invalid for this protocol";
break;
case QNetworkReply::UnknownNetworkError:
errStr = "an unknown network-related error was detected";
break;
case QNetworkReply::UnknownProxyError:
errStr = "an unknown proxy-related error was detected";
break;
case QNetworkReply::UnknownContentError:
errStr = "an unknown error related to the remote content was detected";
break;
case QNetworkReply::ProtocolFailure:
errStr = "a breakdown in protocol was detected (parsing error, invalid or unexpected responses, etc.)";
//.........这里部分代码省略.........
示例12: qDebug
QNetworkReply* QWebDAV::sendWebdavRequest(QUrl url, DAVType type,
QByteArray verb, QIODevice *data,
QString extra, QString extra2)
{
// Prepare the network request and headers
QNetworkRequest request;
QNetworkReply *reply;
request.setUrl(url);
request.setRawHeader(QByteArray("Host"),url.host().toUtf8());
qDebug() << "Sending " << type << "with url: " << url;
// First, find out what type we want
if( type == DAVLIST ) {
// A PROPFIND can include 0, 1 or infinity
QString depthString = extra;
request.setRawHeader(QByteArray("Depth"),
QByteArray(depthString.toLatin1()));
request.setAttribute(QNetworkRequest::User, QVariant("list"));
request.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User+
ATTDATA)
,QVariant(mRequestNumber));
request.setRawHeader(QByteArray("Content-Type"),
QByteArray("text/xml; charset=\"utf-8\""));
request.setRawHeader(QByteArray("Content-Length"),QByteArray("99999"));
reply = sendCustomRequest(request,verb,data);
} else if ( type == DAVGET ) {
request.setRawHeader("User-Agent", "QWebDAV 0.1");
request.setAttribute(QNetworkRequest::User, QVariant("get"));
reply = QNetworkAccessManager::get(request);
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(slotSslErrors(QList<QSslError>)));
} else if ( type == DAVPUT ) {
request.setAttribute(QNetworkRequest::User, QVariant("put"));
if ( mRequestFile.value(mRequestNumber) ) {
request.setAttribute(QNetworkRequest::Attribute(
QNetworkRequest::User+ATTFILE)
,QVariant(mRequestNumber));
request.setAttribute(QNetworkRequest::Attribute(
QNetworkRequest::User+ATTPREFIX)
,QVariant(extra.toLatin1()));
if( extra2 != 0 ) {
// We were given a lock token.
request.setRawHeader(QByteArray("If"),
QByteArray(extra2.toLatin1()));
}
} else {
request.setAttribute(QNetworkRequest::Attribute(
QNetworkRequest::User+ATTDATA)
,QVariant(mRequestNumber));
}
reply = QNetworkAccessManager::put(request,data);
} else if ( type == DAVMKCOL ) {
request.setAttribute(QNetworkRequest::User, QVariant("mkcol"));
reply = sendCustomRequest(request,verb,0);
} else if ( type == DAVDELETE ) {
request.setAttribute(QNetworkRequest::User, QVariant("delete"));
reply = sendCustomRequest(request, verb,0);
} else if ( type == DAVMOVE ) {
request.setAttribute(QNetworkRequest::User, QVariant("move"));
request.setRawHeader(QByteArray("Destination"),
QByteArray(extra.toLatin1()));
request.setRawHeader(QByteArray("Overwrite"),
QByteArray("T"));
if( extra2 != 0 ) {
// We were given (a) lock token(s).
request.setRawHeader(QByteArray("If"),
QByteArray(extra2.toLatin1()));
request.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User+
ATTLOCKTYPE)
,QVariant(extra.replace(mHostname,"").toLatin1()));
}
reply = sendCustomRequest(request, verb,0);
} else if ( type == DAVLOCK) {
request.setAttribute(QNetworkRequest::User,
QVariant("lock"));
// We don't bother setting a timeout, apparently the system defaults
// to 5 minutes anyway.
request.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User+
ATTDATA)
,QVariant(mRequestNumber));
request.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User+
ATTLOCKTYPE)
,QVariant(extra));
reply = sendCustomRequest(request,verb,data);
} else if ( type == DAVUNLOCK) {
QString token = "<"+extra+">";
request.setAttribute(QNetworkRequest::User,
QVariant("unlock"));
request.setRawHeader(QByteArray("Lock-Token"),
QByteArray(token.toLatin1()));
reply = sendCustomRequest(request,verb,0);
} else {
syncDebug() << "Error! DAV Request of type " << type << " is not known!";
reply = 0;
//.........这里部分代码省略.........
示例13: switch
QNetworkReply *NetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData)
{
WebPage *parentPage = qobject_cast<WebPage *>(parent());
QNetworkReply *reply = 0;
QNetworkRequest req = request;
req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
req.setRawHeader("Accept-Language", _acceptLanguage);
KIO::CacheControl cc = KProtocolManager::cacheControl();
switch (cc)
{
case KIO::CC_CacheOnly: // Fail request if not in cache.
req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysCache);
break;
case KIO::CC_Refresh: // Always validate cached entry with remote site.
req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork);
break;
case KIO::CC_Reload: // Always fetch from remote site
req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork);
break;
case KIO::CC_Cache: // Use cached entry if available.
case KIO::CC_Verify: // Validate cached entry with remote site if expired.
default:
req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
break;
}
// WARNING
// There are actually 2 exceptions here handled with QNAM
// instead of KIO that need fixes upstream before removing. They are:
// 1) DeleteOperation
// 2) CustomOperation
switch (op)
{
case QNetworkAccessManager::HeadOperation:
break;
case QNetworkAccessManager::GetOperation:
reply = rApp->adblockManager()->block(req, parentPage);
break;
case QNetworkAccessManager::PutOperation:
break;
case QNetworkAccessManager::PostOperation:
break;
// This particular issue has been solved for KDE Version 4.5.96,
// so we can safely disable this piece of code
#if !KDE_IS_VERSION( 4, 5, 96)
case QNetworkAccessManager::DeleteOperation:
kDebug() << "DELETE OPERATION...";
reply = QNetworkAccessManager::createRequest(op, req, outgoingData);
if (!reply)
kDebug() << "OOOOOOOOOOOOOOOOOOO DELETE REPLY NULL";
break;
case QNetworkAccessManager::CustomOperation:
kDebug() << "CUSTOM OPERATION...";
reply = QNetworkAccessManager::createRequest(op, req, outgoingData);
if (!reply)
kDebug() << "OOOOOOOOOOOOOOOOOOO CUSTOM REPLY NULL";
break;
#endif
default:
kDebug() << "NON EXTANT CASE...";
break;
}
if (!reply)
reply = AccessManager::createRequest(op, req, outgoingData);
if (parentPage && parentPage->hasNetworkAnalyzerEnabled())
emit networkData(op, req, reply);
return reply;
}
示例14: httpHeaderFields
QNetworkRequest ResourceRequest::toNetworkRequest(QObject* originatingFrame) const
{
QNetworkRequest request;
request.setUrl(url());
request.setOriginatingObject(originatingFrame);
const HTTPHeaderMap &headers = httpHeaderFields();
for (HTTPHeaderMap::const_iterator it = headers.begin(), end = headers.end();
it != end; ++it) {
QByteArray name = QString(it->first).toAscii();
QByteArray value = QString(it->second).toAscii();
// QNetworkRequest::setRawHeader() would remove the header if the value is null
// Make sure to set an empty header instead of null header.
if (!value.isNull())
request.setRawHeader(name, value);
else
request.setRawHeader(name, "");
}
// Make sure we always have an Accept header; some sites require this to
// serve subresources
if (!request.hasRawHeader("Accept"))
request.setRawHeader("Accept", "*/*");
switch (cachePolicy()) {
case ReloadIgnoringCacheData:
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork);
break;
case ReturnCacheDataElseLoad:
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
break;
case ReturnCacheDataDontLoad:
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysCache);
break;
case UseProtocolCachePolicy:
// QNetworkRequest::PreferNetwork
default:
break;
}
if (!allowCookies() || !thirdPartyCookiePolicyPermitsForFrame(originatingFrame, url(), firstPartyForCookies())) {
request.setAttribute(QNetworkRequest::CookieSaveControlAttribute, QNetworkRequest::Manual);
request.setAttribute(QNetworkRequest::CookieLoadControlAttribute, QNetworkRequest::Manual);
}
if (!allowCookies())
request.setAttribute(QNetworkRequest::AuthenticationReuseAttribute, QNetworkRequest::Manual);
return request;
}
示例15: qDebug
// Makes a UPnP action request (keeps pointers from the external interface)
int Service::callActionInternal(const QString & actionName, const QMap<QString, QString> * arguments, const QString & prefix)
{
qDebug() << "UPnP::Service: calling remote procedure '" << actionName << "'." << endl;
// Create the data message
//NOTE: we shouldm use serviceId_ instead of serviceType_, but it seems that my router
// (and maybe others) are reporting wrong Ids, while they're gonna accepting only the
// correct ones. This is a decoded reply from my Zyxel:
// Service :
// servicetype = urn:schemas-upnp-org:service:Layer3Forwarding:1
// controlurl = /UD/act?0
// eventsuburl = /?0
// scpdurl = /L3Fwd.xml
// serviceid = urn:upnp-org:serviceId:L3Forwarding1
// this router wants us to use servicetype in the following requests
QString soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
"<"
+ m_szBaseXmlPrefix + ":Envelope xmlns:" + m_szBaseXmlPrefix + "=\"http://schemas.xmlsoap.org/soap/envelope/\""
" "
+ m_szBaseXmlPrefix + ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
" <"
+ m_szBaseXmlPrefix + ":Body>\n"
" <"
+ prefix + ":" + actionName + " xmlns:" + prefix + "=\"" + m_szServiceType + "\">\n";
// Do we have any arguments?
if(arguments != nullptr)
{
// Add the arguments
QMap<QString, QString>::const_iterator it;
for(it = arguments->begin(); it != arguments->end(); ++it)
{
QString argumentName = it.key();
soapMessage += "<" + argumentName + ">" + it.value() + "</" + argumentName + ">";
}
}
// Add the closing tags
soapMessage += " </" + prefix + ":" + actionName + ">\n </" + m_szBaseXmlPrefix + ":Body>\n</" + m_szBaseXmlPrefix + ":Envelope>\n";
// Get an utf8 encoding string
QByteArray content = soapMessage.toUtf8().data();
// Create the HTTP header
QNetworkRequest request;
request.setHeader(QNetworkRequest::ContentTypeHeader, "text/xml");
request.setHeader(QNetworkRequest::ContentLengthHeader, content.size());
request.setRawHeader("SOAPAction", QString("\"%1#%2\"").arg(m_szServiceType, actionName).toUtf8());
QString port;
port.setNum(m_iPort);
request.setRawHeader("HOST", QString("%1:%2").arg(m_szHostname, port).toUtf8());
QUrl url;
url.setHost(m_szHostname);
url.setPort(m_iPort);
request.setUrl(url);
// Send the POST request
m_iPendingRequests++;
QByteArray dummy;
QNetworkReply * pReply = KviNetworkAccessManager::getInstance()->post(request, dummy);
connect(pReply, SIGNAL(finished()), this, SLOT(slotRequestFinished()));
return 0;
}