void Groups::finishedFetchingGroups() { QNetworkReply *reply = static_cast<QNetworkReply *>(sender()); if (reply->hasRawHeader("Backoff")) d->api->startBackoff(QString::fromLatin1(reply->rawHeader("Backoff").constData()).toInt()); else if (reply->hasRawHeader("Retry-After")) d->api->startBackoff(QString::fromLatin1(reply->rawHeader("Retry-After").constData()).toInt()); if (reply->error() == QNetworkReply::NoError) { QString nextPage; QXmlStreamReader xmlReader(reply); while (!xmlReader.atEnd() && !xmlReader.hasError()) { const QXmlStreamReader::TokenType tt = xmlReader.readNext(); if (tt == QXmlStreamReader::StartElement && xmlReader.name() == QStringLiteral("entry")) { QString label; int groupId = -1; while (!xmlReader.atEnd() && !xmlReader.hasError()) { const QXmlStreamReader::TokenType tt = xmlReader.readNext(); if (tt == QXmlStreamReader::StartElement && xmlReader.name() == QStringLiteral("title")) label = xmlReader.readElementText(QXmlStreamReader::IncludeChildElements); else if (tt == QXmlStreamReader::StartElement && xmlReader.name() == QStringLiteral("groupID")) { bool ok = false; groupId = xmlReader.readElementText(QXmlStreamReader::IncludeChildElements).toInt(&ok); if (groupId < 1) groupId = -1; } else if (tt == QXmlStreamReader::EndElement && xmlReader.name() == QStringLiteral("entry")) break; } if (!label.isEmpty() && groupId > 0) d->groups.insert(groupId, label); } else if (tt == QXmlStreamReader::StartElement && xmlReader.name() == QStringLiteral("link")) { const QXmlStreamAttributes attrs = xmlReader.attributes(); if (attrs.hasAttribute(QStringLiteral("rel")) && attrs.hasAttribute(QStringLiteral("href")) && attrs.value(QStringLiteral("rel")) == QStringLiteral("next")) nextPage = attrs.value(QStringLiteral("href")).toString(); } else if (tt == QXmlStreamReader::EndElement && xmlReader.name() == QStringLiteral("feed")) break; } if (!nextPage.isEmpty()) d->requestZoteroUrl(nextPage); else { d->busy = false; d->initialized = true; emit finishedLoading(); } } else { qCWarning(LOG_KBIBTEX_NETWORKING) << reply->errorString(); ///< something went wrong d->busy = false; d->initialized = false; emit finishedLoading(); } }
void RequestModel::update() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); if (!reply) return; int offset; for (offset = m_requests.count() - 1; offset >= 0; --offset) { if (m_requests[offset].reply == reply) break; } if (offset < 0) return; // Save reply headers foreach (const QByteArray &header, reply->rawHeaderList() ) { QPair<QByteArray, QByteArray> pair(header, reply->rawHeader(header)); m_requests[offset].replyHeaders.append(pair); } // Save reply info to be displayed int status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt(); QString reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); m_requests[offset].response = QString(QLatin1String("%1 %2")).arg(status).arg(reason); m_requests[offset].length = reply->header(QNetworkRequest::ContentLengthHeader).toInt(); m_requests[offset].contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); if (status == 302) { QUrl target = reply->attribute( QNetworkRequest::RedirectionTargetAttribute ).toUrl(); m_requests[offset].info = tr("Redirect: %1").arg(target.toString()); } }
int main(int argc, char **argv) { QCoreApplication app(argc, argv); QNetworkAccessManager manager; if (argc != 2) { std::cout << "usage: " << argv[0] << " <url>" << std::endl; return 0; } QUrl url(app.arguments().value(1)); QNetworkRequest request(url); QNetworkReply *reply = manager.get(request); app.connect(reply, SIGNAL(finished()), SLOT(quit())); app.exec(); QFile outfile("request.header"); if (outfile.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream stream(&outfile); QList<QByteArray> list = reply->rawHeaderList(); foreach (QByteArray name, list) { stream << name << ": " << reply->rawHeader(name) << endl; }
void GetFileUploadedBytesRequest::requestSuccess(QNetworkReply &reply) { QString accept_ranges_header = reply.rawHeader("Accept-Ranges"); // printf ("accept_ranges_header = %s\n", toCStr(accept_ranges_header)); if (accept_ranges_header != "bytes") { // Chunked uploading is not supported on the server emit success(false, 0); return; } json_error_t error; json_t* root = parseJSON(reply, &error); if (!root) { qWarning("GetFileUploadedBytesRequest: failed to parse json:%s\n", error.text); emit failed(ApiError::fromJsonError()); return; } QScopedPointer<json_t, JsonPointerCustomDeleter> json(root); QMap<QString, QVariant> dict = mapFromJSON(json.data(), &error); quint64 uploaded_bytes = dict["uploadedBytes"].toLongLong(); // printf ("uploadedBytes = %lld\n", uploaded_bytes); emit success(true, uploaded_bytes); }
QByteArray QNetworkReplyProto::rawHeader(const QByteArray &headerName) const { QNetworkReply *item = qscriptvalue_cast<QNetworkReply*>(thisObject()); if (item) item->rawHeader(headerName); return QByteArray(); }
void Sound::replyFinished() { QNetworkReply* reply = reinterpret_cast<QNetworkReply*>(sender()); // replace our byte array with the downloaded data QByteArray rawAudioByteArray = reply->readAll(); // foreach(QByteArray b, reply->rawHeaderList()) // qDebug() << b.constData() << ": " << reply->rawHeader(b).constData(); if (reply->hasRawHeader("Content-Type")) { QByteArray headerContentType = reply->rawHeader("Content-Type"); // WAV audio file encountered if (headerContentType == "audio/x-wav" || headerContentType == "audio/wav" || headerContentType == "audio/wave") { QByteArray outputAudioByteArray; interpretAsWav(rawAudioByteArray, outputAudioByteArray); downSample(outputAudioByteArray); } else { // Process as RAW file downSample(rawAudioByteArray); } } else { qDebug() << "Network reply without 'Content-Type'."; } _hasDownloaded = true; }
void DriveManager::handleUploadRequestFinished () { QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ()); if (!reply) return; reply->deleteLater (); QString path = Reply2FilePath_.take (reply); const int code = reply-> attribute (QNetworkRequest::HttpStatusCodeAttribute).toInt (); if (code != 200) { qWarning () << Q_FUNC_INFO << "upload initiating failed with code:" << code; return; } emit uploadStatusChanged (tr ("Uploading..."), path); QFile *file = new QFile (path); if (!file->open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open file: " << file->errorString (); return; } QUrl url (reply->rawHeader ("Location")); QNetworkRequest request (url); #ifdef HAVE_MAGIC request.setHeader (QNetworkRequest::ContentTypeHeader, magic_file (Magic_, path.toUtf8 ())); #endif request.setHeader (QNetworkRequest::ContentLengthHeader, QString::number (QFileInfo (path).size ()).toUtf8 ()); QNetworkReply *uploadReply = Core::Instance ().GetProxy ()-> GetNetworkAccessManager ()->put (request, file); file->setParent (uploadReply); Reply2FilePath_ [uploadReply] = path; connect (uploadReply, SIGNAL (finished ()), this, SLOT (handleUploadFinished ())); connect (uploadReply, SIGNAL (error (QNetworkReply::NetworkError)), this, SLOT (handleUploadError (QNetworkReply::NetworkError))); connect (uploadReply, SIGNAL (uploadProgress (qint64, qint64)), this, SLOT (handleUploadProgress (qint64, qint64))); }
/* * loadScript 方法 * @param string js路径(支持本地路径以及http与https协议下远程js获取) * @param function 调用函数 * @return * 如果第二个参数不存在, load 失败,返回 false 。 * 如果第二个参数不存在, load 成功,则返回 true 。 * 如果第二参数存在,则立即调用内部函数,返回执行结果。 * load的内容将以回调函数参数传入: * @param bool err 表明是否正常读取内容 * @param function callback 回一个load函数引用 */ QScriptValue ScriptBinding::loadScript(QScriptContext *context, QScriptEngine *interpreter) { QScriptValue path = context->argument(0); QScriptValue scriptFunc = context->argument(1); if (context->argumentCount() == 0) return QScriptValue(false); if (!path.isString()) return QScriptValue(false); QString pathStr = path.toString().toLower().trimmed(); QString content = ""; bool err = false; // 如果是 HTTP 、 HTTPS 则尝试从远端获取源码 if (pathStr.indexOf("http://") == 0 || pathStr.indexOf("https://") == 0 ) { QNetworkReply* reply; QNetworkAccessManager* manager = new QNetworkAccessManager(); reply = manager->get(QNetworkRequest(QUrl(pathStr))); QEventLoop eventLoop; connect(manager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit())); eventLoop.exec(); QByteArray responseData; responseData = reply->readAll(); // 通过 Content-Type 来嗅探字节流编码 // 默认为 utf-8 编码 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 = "utf-8"; } else { charset = charsetRegExp.cap(1); } } else { charset = "utf-8"; } QTextStream stream(responseData); stream.setCodec(getCodec(charset)); content = QString(stream.readAll()); } else {
void GetDirentsRequest::requestSuccess(QNetworkReply& reply) { json_error_t error; QString dir_id = reply.rawHeader("oid"); if (dir_id.length() != 40) { emit failed(ApiError::fromHttpError(500), repo_id_); return; } // this extra header column only supported from v4.2 seahub readonly_ = reply.rawHeader("dir_perm") == "r"; json_t *root = parseJSON(reply, &error); if (!root) { qDebug("GetDirentsRequest: failed to parse json:%s\n", error.text); emit failed(ApiError::fromJsonError(), repo_id_); return; } QScopedPointer<json_t, JsonPointerCustomDeleter> json(root); QList<SeafDirent> dirents; dirents = SeafDirent::listFromJSON(json.data(), &error); emit success(readonly_, dirents, repo_id_); }
void YandexNarodUploadJob::uploadReply() { m_timer.stop(); debug() << "uploadReply"; QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); Q_ASSERT(reply); if (!processReply(reply)) return; QByteArray data = reply->readAll(); QVariantMap map = Json::parse(data).toMap(); debug() << "upload" << data << map; debug() << reply->rawHeaderList(); debug() << "upload" << reply->rawHeader("Set-Cookie"); someStrangeSlot(); }
void ImgurUploader::finished() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); reply->deleteLater(); QString fileName = reply->property("fileName").toString(); if (reply->error() != QNetworkReply::NoError) { if (reply->error() == QNetworkReply::OperationCanceledError) { emit error(ImageUploader::CancelError, "", fileName); } else if (reply->error() == QNetworkReply::ContentOperationNotPermittedError || reply->error() == QNetworkReply::AuthenticationRequiredError) { refreshAuthorization(mSettings["refresh_token"].toString(), [&](bool result) { if (result) { QTimer::singleShot(50, this, &ImgurUploader::retry); } else { cancel(); emit error(ImageUploader::AuthorizationError, tr("Imgur user authentication failed"), fileName); } }); } else { emit error(ImageUploader::NetworkError, reply->errorString(), fileName); } return; } if (reply->rawHeader("X-RateLimit-Remaining") == "0") { emit error(ImageUploader::HostError, tr("Imgur upload limit reached"), fileName); return; } QJsonObject imgurResponse = QJsonDocument::fromJson(reply->readAll()).object(); if (imgurResponse.value("success").toBool() == true && imgurResponse.value("status").toInt() == 200) { QJsonObject imageData = imgurResponse.value("data").toObject(); emit uploaded(fileName, imageData["link"].toString(), imageData["deletehash"].toString()); } else { emit error(ImageUploader::HostError, tr("Imgur error"), fileName); } }
void YandexNarodUploadJob::storageReply() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); Q_ASSERT(reply); if (!processReply(reply)) return; QByteArray data = reply->readAll(); QVariantMap map = m_someData = Json::parse(data).toMap(); debug() << "storage" << map; debug() << "storage" << reply->rawHeader("Set-Cookie"); QUrl url(map.value("url").toString()); url.addQueryItem("tid", map.value("hash").toString()); int boundaryTemp[] = { qrand(), qrand(), qrand() }; QByteArray boundary = QByteArray::fromRawData(reinterpret_cast<char *>(boundaryTemp), sizeof(boundaryTemp)).toHex(); m_data = setCurrentIndex(0); m_data = new YandexNarodBuffer(fileName(), m_data, boundary, this); if (!m_data->open(QIODevice::ReadOnly)) { setError(IOError); setErrorString(tr("Could not open file %1").arg(fileName())); return; } setState(Started); #if HAS_NO_TOKEN_AUTHORIZATION QNetworkRequest request(m_request); request.setUrl(url); #else YandexRequest request(url); #endif request.setRawHeader("Content-Type", "multipart/form-data, boundary=" + boundary); request.setRawHeader("Content-Length", QString::number(m_data->size()).toLatin1()); QNetworkReply *uploadNetworkReply = YandexNarodFactory::networkManager()->post(request, m_data); connect(m_data, SIGNAL(destroyed()), uploadNetworkReply, SLOT(deleteLater())); connect(uploadNetworkReply, SIGNAL(finished()), this, SLOT(uploadReply())); m_timer.start(); }
void ChatService::slotLoginRequestFinished() { qDebug() << "connected to facebook"; qDebug() << _network->cookieJar()->cookiesForUrl(QUrl(FACEBOOK_URL)).count() << " cookies"; QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); if ( !reply ) return; qDebug() << reply->readAll(); qDebug() << reply->errorString(); // parse new cookies QList<QNetworkCookie> cookies; QStringList rawcookies = QString(reply->rawHeader("Set-Cookie")).split("\n"); foreach (QString rawcookie, rawcookies) { qDebug() << "cookie header: " << rawcookie; cookies << QNetworkCookie::parseCookies(rawcookie.toAscii()); }
void GetFileDownloadLinkRequest::requestSuccess(QNetworkReply& reply) { QString reply_content(reply.readAll()); QString oid; if (reply.hasRawHeader("oid")) oid = reply.rawHeader("oid"); do { if (reply_content.size() <= 2) break; reply_content.remove(0, 1); reply_content.chop(1); QUrl new_url(reply_content); if (!new_url.isValid()) break; file_id_ = oid; emit success(reply_content); return; } while (0); emit failed(ApiError::fromHttpError(500)); }
/** * Called after response from twitter */ void QTweetNetBase::reply() { QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); // prep m_response for finished() signal if (reply) { m_response = reply->readAll(); } else { m_response.clear(); } // ALWAYS emit a finished signal no matter what happens emit finished(m_response); // now analyze the response if (reply) { QString rateLimit(reply->rawHeader("X-Rate-Limit-Limit")); QString rateRemaining(reply->rawHeader("X-Rate-Limit-Remaining")); QString limitRest(reply->rawHeader("X-Rate-Limit-Reset")); uint timeToReset = limitRest.toLongLong()- QDateTime::currentDateTime().toTime_t(); QString contentType(reply->rawHeader("content-type")); bool contentTypeHasJson = contentType.contains("application/json", Qt::CaseInsensitive); if (reply->error() == QNetworkReply::NoError) { if (isJsonParsingEnabled() && contentTypeHasJson) { parseJson(m_response); } } else { //dump error qDebug() << "Network error: " << reply->error(); qDebug() << "Error string: " << reply->errorString(); qDebug() << "Error response: " << m_response; //HTTP status code int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); //prep error QTweetNetError* err = 0; if (!contentTypeHasJson) { err = new QTweetHttpError(httpStatus, m_response); } else { //try to json parse the error response QJson::Parser parser; bool ok; QVariant json = parser.parse(m_response, &ok); QVariantMap errMsgMap = json.toMap(); QMap<int, QString> twitterErrors; if (ok) { // here are a few sample responses we've seen: //{"request":"\/1\/users\/search.json?q=&per_page=20&page=1","error":"Client must provide a 'q' parameter with a value."} //{"error":"You must enter a query."} //{"errors":[{"message": "...", "code": 34}]} QList<QVariant> errors = errMsgMap["errors"].toList(); QList<QVariant>::iterator it = errors.begin(); while (it != errors.end()) { QVariantMap error = (*it).toMap(); int errorCode = error["code"].toInt(); QString errorMessage = error["message"].toString(); twitterErrors[errorCode] = errorMessage; it++; } if (twitterErrors.size() > 0) { err = new QTweetServiceErrors(httpStatus, m_response, json, twitterErrors); } else { qDebug() << "Parsing json ok but twitter errors not found"; err = new QTweetRawServiceError(httpStatus, m_response, json); } } else { qDebug() << "Unable to parse json in response"; err = new QTweetHttpError(httpStatus, m_response); } } //finally emit the error signal if (err) { emit error(*err); err->deleteLater(); } else { Q_ASSERT(false); } } reply->deleteLater(); } }
void YandexNarodUploadJob::progressReply() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); Q_ASSERT(reply); if (!processReply(reply)) return; QByteArray data = reply->readAll(); #if HAS_NO_TOKEN_AUTHORIZATION int start = data.indexOf('{'); int end = data.lastIndexOf('}'); QVariantMap map = Json::parse(data.mid(start, end - start + 1)).toMap(); #else QVariant tmpVar; int dataBegin = data.indexOf('(') + 1; int dataEnd = data.lastIndexOf(')'); int dataLength = dataEnd - dataBegin; if (dataBegin < 0 || dataEnd < 0 || dataLength < 0) { dataBegin = 0; dataLength = data.length(); } Json::parseRecord(tmpVar, data.constData() + dataBegin, &dataLength); QVariantMap map = tmpVar.toMap(); #endif debug() << "progress" << reply->request().url() << data << map; debug() << "progress" << reply->rawHeader("Set-Cookie"); int newProgress = fileSize() * (map.value("percent").toDouble() / 100.0); if (newProgress > progress()) setFileProgress(newProgress); QString status = map.value("status").toString(); if (status == "upload") { m_timer.start(); // { // "tid": "1263553646SvsF9FFimF5thmoM2kGTwxL9", // "status": "upload", // "percent": "94.11", // "ipercent": 94, // "random": "1263553668S4gHxbB2nJSd2clhhfYimsfM", // "time": { "min": "0","sec": "01" } // } } else if (status == "done" && state() != Finished) { // { // "tid": "1263553646SvsF9FFimF5thmoM2kGTwxL9", // "status": "done", // "fids": "8433938", // "files": [{ "fid": "8433938", "hash": "16928325000", "name": "Makefile", "size": "146305" }], // "percent": "100.00", // "ipercent": 100, // "random": "1263553670cshMPkykOsHbaCnIQ5ehEOKd", // "time": { "min": "0","sec": "00" } // } setState(Finished); QVariantMap varMap = map.value("files").toList().value(0).toMap(); if (!varMap.isEmpty() && chatUnit()) { debug() << "done" << chatUnit()->title() << varMap; QString url(QLatin1String("http://narod.ru/disk/")); url += varMap.value("hash").toString(); url += QLatin1Char('/'); url += varMap.value("name").toString(); url += QLatin1String(".html"); debug() << url; QString sendmsg = Config().group("yandex").group("narod") .value("template", tr("File sent: %N (%S bytes)\n%U", "Don't remove format arguments")); sendmsg.replace("%N", varMap.value("name").toString()); sendmsg.replace("%U", url); sendmsg.replace("%S", varMap.value("size").toString()); //Append message to chatunit Message msg(sendmsg); msg.setIncoming(false); msg.setProperty("service", true); if (ChatSession *s = ChatLayer::get(chatUnit(), false)) s->appendMessage(msg); msg.setProperty("service", false); chatUnit()->account()->getUnitForSession(chatUnit())->send(msg); } } }
QPair<bool, QPair<QString, QByteArray>> blockDownloadExtractFilenameAndData(QNetworkReply & reply) { auto res = blockDownloadExtractData(reply); //QNetworkRequest::ContentDispositionHeader is broken – https://bugreports.qt.io/browse/QTBUG-45610 auto filename = copyInfoFromHeader(reply.rawHeader("Content-Disposition"), "filename"); return {res.first, {filename, res.second}}; }
void GetSharedLinkRequest::requestSuccess(QNetworkReply& reply) { QString reply_content(reply.rawHeader("Location")); emit success(reply_content, repo_id_); }
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())); }