Exemple #1
0
void CMediaSourceServerProfile::sendTrackList(std::string const& trackList)
{
   LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__ );
   static const int packetSize = MEDIA_TRACKLIST_PACKET_SIZE;
   div_t divresult = div(trackList.size(), packetSize);
   int packetsNumber = divresult.quot + (divresult.rem == 0 ? 0 : 1);
   LOG4CPLUS_INFO(msLogger, "sendTrackList() total packets number = " + convertIntegerToString(packetsNumber));
   LOG4CPLUS_INFO(msLogger, "sendTrackList() full packets number = " + convertIntegerToString(divresult.quot));
   prepareRequest(DECLARE_TRACKLIST_PACKETS_NUMBER, true, convertIntegerToString(packetsNumber));
   int offset = 0;
   for (int i = 0; i < divresult.quot; i++) 
   {
      LOG4CPLUS_INFO(msLogger, "sendTrackList() sending packet number: " + convertIntegerToString(i));
      offset = i * packetSize;
      LOG4CPLUS_INFO(msLogger, "sendTrackList() sending packet, offset is: " + convertIntegerToString(offset));
      LOG4CPLUS_INFO(msLogger, "sendTrackList() sending packet, content is: " + trackList.substr(offset, packetSize));
      prepareRequest(SENDTRACKLIST, true, trackList.substr(offset, packetSize));
   }
   offset = packetSize * divresult.quot;
   if (divresult.rem != 0)
   {
      LOG4CPLUS_INFO(msLogger, "sendTrackList() sending last packet: " + trackList.substr(offset));
      prepareRequest(SENDTRACKLIST, true, trackList.substr(offset));
   }
}
Exemple #2
0
bool QHttpNetworkConnectionPrivate::dequeueRequest(QAbstractSocket *socket)
{
    Q_ASSERT(socket);

    int i = indexOf(socket);

    if (!highPriorityQueue.isEmpty()) {
        // remove from queue before sendRequest! else we might pipeline the same request again
        HttpMessagePair messagePair = highPriorityQueue.takeLast();
        if (!messagePair.second->d_func()->requestIsPrepared)
            prepareRequest(messagePair);
        channels[i].request = messagePair.first;
        channels[i].reply = messagePair.second;
        return true;
    }

    if (!lowPriorityQueue.isEmpty()) {
        // remove from queue before sendRequest! else we might pipeline the same request again
        HttpMessagePair messagePair = lowPriorityQueue.takeLast();
        if (!messagePair.second->d_func()->requestIsPrepared)
            prepareRequest(messagePair);
        channels[i].request = messagePair.first;
        channels[i].reply = messagePair.second;
        return true;
    }
    return false;
}
void CMediaControlServerProfile::play(std::string const& trackName, std::string const& trackUid, std::string const& avform)
{

    LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__);
    LOG4CPLUS_INFO(msLogger,  "trackName: " + trackName + "avform: "  + avform + "trackUid: " + trackUid);
    std::string mTrackName = trackName;
    int position = mTrackName.find(" ");
    while ( position != std::string::npos )
    {
        mTrackName.replace(position, 1, "+" );
        position = mTrackName.find( " ", position + 1 );
    }
    int randomNum = rand() % 1000 + 1;
    std::stringstream out;
    out << randomNum;
    std::string streamName = mStreamName + mTrackName.substr(0, mTrackName.find(".")-1) + out.str();
    LOG4CPLUS_TRACE(msLogger, "stream name: "+streamName);
    mPath = mpAppCallbacks->onMediaPathRequest();
    std::string path = mPath + trackName;
    std::string source = mRtsp + mIp + ":" + mPort + "/" + streamName;
    if (mpServControl->sendPlay(mPort, path, streamName, avform))
    {
        prepareRequest(PLAY, true, trackName, trackUid, source, avform);
        mpAppCallbacks->onServerPlay(trackName, trackUid, source, avform);
    }
}
void RpcClientImpl::beginCall(IComposer& r, IRemoteProcedure& method, IDecomposer** argv, unsigned argc)
{
    if (_socket.selector() == 0)
        throw std::logic_error("cannot run async rpc request without a selector");

    if (_proc)
        throw std::logic_error("asyncronous request already running");

    _proc = &method;

    prepareRequest(method.name(), argv, argc);

    if (_socket.isConnected())
    {
        try
        {
            _stream.buffer().beginWrite();
        }
        catch (const IOError&)
        {
            log_debug("write failed, connection is not active any more");
            _socket.beginConnect(_addr, _port);
        }
    }
    else
    {
        log_debug("not yet connected - do it now");
        _socket.beginConnect(_addr, _port);
    }

    _scanner.begin(_deserializer, r);
}
Exemple #5
0
static int prepareExtendRequest(KSI_NetworkClient *client, KSI_ExtendReq *req, KSI_RequestHandle **handle) {
	int res = KSI_UNKNOWN_ERROR;
	KSI_ExtendPdu *pdu = NULL;

	res = KSI_ExtendReq_enclose(req, client->extUser, client->extPass, &pdu);
	if (res != KSI_OK) goto cleanup;

	res = prepareRequest(
			client,
			pdu,
			(int (*)(void *, unsigned char **, unsigned *))KSI_ExtendPdu_serialize,
			handle,
			((KSI_HttpClient*)client)->urlExtender,
			"Extend request");

	if (res != KSI_OK) goto cleanup;

	res = KSI_OK;

cleanup:

	KSI_ExtendPdu_setRequest(pdu, NULL);
	KSI_ExtendPdu_free(pdu);

	return res;
}
Exemple #6
0
bool AWebservice::getForumList (AForumGroupInfoList& list)
{
	QString data;
	data += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
	data += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
	data += "  <soap:Body>\r\n";
	data += "    <GetForumList xmlns=\"http://rsdn.ru/Janus/\">\r\n";
	data += "      <forumRequest>\r\n";
	data += (QString)"        <userName>" + m_rsdn_login    + "</userName>\r\n";
	data += (QString)"        <password>" + m_rsdn_password + "</password>\r\n";
	data += "        <forumsRowVersion>AAAAAAAAAAA=</forumsRowVersion>\r\n";
	data += "      </forumRequest>\r\n";
	data += "    </GetForumList>\r\n";
	data += "  </soap:Body>\r\n";
	data += "</soap:Envelope>\r\n";

	QNetworkRequest request;
	prepareRequest(request, m_rsdn_proto, "GetForumList", data.toUtf8().size());

	if (makeRequest(request, data) == false)
		return false;

	parseForumList(m_body, list);

	return true;
}
void EnginioClientConnectionPrivate::uploadChunk(EnginioReplyState *ereply, QIODevice *device, qint64 startPos)
{
    QUrl serviceUrl = _serviceUrl;
    {
        QString path;
        QByteArray errorMsg;
        if (!getPath(ereply->data(), Enginio::FileChunkUploadOperation, &path, &errorMsg).successful())
            Q_UNREACHABLE(); // sequential upload can not have an invalid path!
        serviceUrl.setPath(path);
    }

    QNetworkRequest req = prepareRequest(serviceUrl);
    req.setHeader(QNetworkRequest::ContentTypeHeader, EnginioString::Application_octet_stream);

    // Content-Range: bytes {chunkStart}-{chunkEnd}/{totalFileSize}
    qint64 size = device->size();
    qint64 endPos = qMin(startPos + _uploadChunkSize, size);
    req.setRawHeader(EnginioString::Content_Range,
                     QByteArray::number(startPos) + EnginioString::Minus
                     + QByteArray::number(endPos) + EnginioString::Div
                     + QByteArray::number(size));

    // qDebug() << "Uploading chunk from " << startPos << " to " << endPos << " of " << size;

    Q_ASSERT(device->isOpen());

    ChunkDevice *chunkDevice = new ChunkDevice(device, startPos, _uploadChunkSize);
    chunkDevice->open(QIODevice::ReadOnly);

    QNetworkReply *reply = networkManager()->put(req, chunkDevice);
    chunkDevice->setParent(reply);
    _chunkedUploads.insert(reply, qMakePair(device, endPos));
    ereply->setNetworkReply(reply);
    _connections.append(QObject::connect(reply, &QNetworkReply::uploadProgress, UploadProgressFunctor(this, reply)));
}
Exemple #8
0
/**
 * @fn sendReportUsingGithub
 */
void GithubModule::sendReportUsingGithub(const QMap<QString, QString> info)
{
    if (debug) qDebug() << "[GithubModule]" << "[sendReportUsingGithub]";

    // authentication
    QString headerData;
    if (info.contains(QString("userdata")))
        headerData = QString("token ") + info[QString("userdata")];
    else {
        QString concatenated = info[QString("username")] + QString(":") + info[QString("password")];
        QByteArray userData = concatenated.toLocal8Bit().toBase64();
        headerData = QString("Basic ") + userData;
    }
    // text
    QByteArray text = prepareRequest(info[QString("title")], info[QString("body")]);
    QByteArray textSize = QByteArray::number(text.size());
    // sending request
    QNetworkRequest request = QNetworkRequest(parseString(dynamic[QString("ISSUES_URL")]));
    request.setRawHeader("Authorization", headerData.toLocal8Bit());
    request.setRawHeader("User-Agent", "reportabug");
    request.setRawHeader("Host", "api.github.com");
    request.setRawHeader("Accept", "*/*");
    request.setRawHeader("Content-Type", "application/vnd.github.VERSION.raw+json");
    request.setRawHeader("Content-Length", textSize);
    QNetworkAccessManager *manager = new QNetworkAccessManager;
    manager->post(request, text);
    disconnect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(githubFinished(QNetworkReply *)));
    connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(githubFinished(QNetworkReply *)));
}
Exemple #9
0
bool AWebservice::getUserList (const QString& last_row_version, AUserInfoList& list, QString& row_version)
{
	QString data;
	data += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
	data += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
	data += "  <soap:Body>\r\n";
	data += "    <GetNewUsers xmlns=\"http://rsdn.ru/Janus/\">\r\n";
	data += "      <userRequest>\r\n";
	data += (QString)"        <userName>"       + m_rsdn_login     + "</userName>\r\n";
	data += (QString)"        <password>"       + m_rsdn_password  + "</password>\r\n";
	data += (QString)"        <lastRowVersion>" + last_row_version + "</lastRowVersion>\r\n";
	data += "        <maxOutput>0</maxOutput>\r\n";
	data += "      </userRequest>\r\n";
	data += "    </GetNewUsers>\r\n";
	data += "  </soap:Body>\r\n";
	data += "</soap:Envelope>\r\n";

	QNetworkRequest request;
	prepareRequest(request, m_rsdn_proto, "GetNewUsers", data.toUtf8().size());

	if (makeRequest(request, data) == false)
		return false;

	QString result = parseUserList(m_body, list, row_version);
	if (result.length() > 0)
	{
		m_error = result;
		return false;
	}

	return true;
}
bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtrWillBeRawPtr<Blob>& data, int& payloadLength)
{
    ASSERT(data);
    unsigned long long entitySize = data->size();
    if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize)
        return false;

    ResourceRequest request(beaconURL);
    prepareRequest(frame, request);

    RefPtr<FormData> entityBody = FormData::create();
    if (data->hasBackingFile())
        entityBody->appendFile(toFile(data.get())->path());
    else
        entityBody->appendBlob(data->uuid(), data->blobDataHandle());

    request.setHTTPBody(entityBody.release());

    AtomicString contentType;
    const String& blobType = data->type();
    if (!blobType.isEmpty() && isValidContentType(blobType))
        request.setHTTPContentType(AtomicString(contentType));

    issueRequest(frame, request);
    payloadLength = entitySize;
    return true;
}
void HttpClientImpl::call(IComposer& r, IRemoteProcedure& method, IDecomposer** argv, unsigned argc)
{
    _proc = &method;

    prepareRequest(method.name(), argv, argc);

    _client.execute(_request);

    _scanner.begin(_deserializer, r);

    char ch;
    std::istream& is = _client.in();
    while (is.get(ch))
    {
        if (_scanner.advance(ch))
        {
            log_debug("scanner finished");
            _proc = 0;
            _scanner.finalizeReply();
            return;
        }
    }

    throw std::runtime_error("unexpected end of data");
}
void CMediaControlServerProfile::changeHighlightedTrack(int newPosition)
{
    LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__);
    std::stringstream out;
    out << newPosition;
    std::string newPos = out.str();
    prepareRequest(CHANGETRACK, true, newPos);
}
void CMediaControlServerProfile::resume() {
    LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__);
    if (mpServControl->sendCommand(mpServControl->mResume))
    {
        prepareRequest(RESUME, false);
        mpAppCallbacks->onServerResume();
    }
}
/**
 * Initiates a basic urlencoded form submission
 * @param aFile Fully qualified file URL
 * @param aData StringMap with the args and values
 */
void HttpConnection::download(const StringMap& postData) {
	requestBody.clear();

	for(auto& i: postData)
		requestBody += "&" + Util::encodeURI(i.first) + "=" + Util::encodeURI(i.second);

	if (!requestBody.empty()) requestBody = requestBody.substr(1);
	prepareRequest(TYPE_POST);
}
void FrameFetchContext::dispatchWillSendRequest(unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo)
{
    // For initial requests, prepareRequest() is called in
    // willStartLoadingResource(), before revalidation policy is determined.
    // That call doesn't exist for redirects, so call preareRequest() here.
    if (!redirectResponse.isNull())
        prepareRequest(identifier, request, redirectResponse);
    TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD, "data", InspectorSendRequestEvent::data(identifier, frame(), request));
    InspectorInstrumentation::willSendRequest(frame(), identifier, masterDocumentLoader(), request, redirectResponse, initiatorInfo);
}
void HttpClientImpl::beginCall(IComposer& r, IRemoteProcedure& method, IDecomposer** argv, unsigned argc)
{
    _proc = &method;

    prepareRequest(method.name(), argv, argc);

    _client.beginExecute(_request);

    _scanner.begin(_deserializer, r);
}
Exemple #17
0
static int prepareAggregationRequest(KSI_NetworkClient *client, KSI_AggregationReq *req, KSI_RequestHandle **handle) {
	int res = KSI_UNKNOWN_ERROR;
	KSI_AggregationPdu *pdu = NULL;
	KSI_Integer *pReqId = NULL;
	KSI_Integer *reqId = NULL;
	TcpClient_Endpoint *endp = NULL;

	if (client == NULL || req == NULL || handle == NULL) {
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}

	endp = client->aggregator->implCtx;

	if (endp->host == NULL || endp->port == 0) {
		res = KSI_AGGREGATOR_NOT_CONFIGURED;
		goto cleanup;
	}

	res = KSI_AggregationReq_getRequestId(req, &pReqId);
	if (res != KSI_OK) goto cleanup;

	if (pReqId == NULL) {
		res = KSI_Integer_new(client->ctx, ++client->requestCount, &reqId);
		if (res != KSI_OK) goto cleanup;

		res = KSI_AggregationReq_setRequestId(req, reqId);
		if (res != KSI_OK) goto cleanup;

		reqId = NULL;
	}

	res = KSI_AggregationReq_enclose(req, client->aggregator->ksi_user, client->aggregator->ksi_pass, &pdu);
	if (res != KSI_OK) goto cleanup;

	res = prepareRequest(
			client,
			pdu,
			(int (*)(void *, unsigned char **, size_t *))KSI_AggregationPdu_serialize,
			handle,
			endp->host,
			endp->port,
			"Aggregation request");
	if (res != KSI_OK) goto cleanup;

	res = KSI_OK;

cleanup:

	KSI_AggregationPdu_setRequest(pdu, NULL);
	KSI_AggregationPdu_free(pdu);

	return res;
}
/**
 * Performs a do asynchronous get operation.
 *
 * @brief AbstractHTTPClient::doAsyncGet Asynchronous get operation.
 * @param url a string that represents the do asynchronous get operation.
 * @param accept.
 * @return returns a QNetworkReply.
 */
QNetworkReply* AbstractHTTPClient::doAsyncGet(QString &url, const char* accept) {
    QUrl _url(url);
    QNetworkRequest request( _url );

    prepareRequest(request);
    request.setRawHeader(QByteArray("accept"), QByteArray(accept));

    QNetworkReply *reply = manager->get( request );

    return reply;
}
void SeafileApiClient::get(const QUrl& url)
{
    QNetworkRequest request(url);
    prepareRequest(&request);

    reply_ = na_mgr_->get(request);

    connect(reply_, SIGNAL(sslErrors(const QList<QSslError>&)),
            this, SLOT(onSslErrors(const QList<QSslError>&)));

    connect(reply_, SIGNAL(finished()), this, SLOT(httpRequestFinished()));
}
Exemple #20
0
void RpcClientImpl::call(IComposer& r, IRemoteProcedure& method, IDecomposer** argv, unsigned argc)
{
    _proc = &method;

    prepareRequest(_proc->name(), argv, argc);

    if (!_socket.isConnected())
    {
        _socket.setTimeout(_connectTimeout);
        _socket.connect(_addrInfo);
        if (_ssl)
            _socket.sslConnect();
    }

    _socket.setTimeout(timeout());

    try
    {
        _stream.flush();

        _scanner.begin(_deserializer, r);

        StreamBuffer& sb = _stream.buffer();

        while (true)
        {
            int ch = sb.sbumpc();
            if (ch == StreamBuffer::traits_type::eof())
            {
                _proc = 0;
                cancel();
                throw std::runtime_error("reading result failed");
            }

            if ( _scanner.advance( StreamBuffer::traits_type::to_char_type(ch) ) )
            {
                _proc = 0;
                _scanner.finish();
                break;
            }
        }
    }
    catch (const RemoteException&)
    {
        throw;
    }
    catch (const std::exception& e)
    {
        cancel();
        throw;
    }
}
void FrameFetchContext::willStartLoadingResource(unsigned long identifier, ResourceRequest& request, Resource::Type type)
{
    TRACE_EVENT_ASYNC_BEGIN1("blink.net", "Resource", identifier, "data", loadResourceTraceData(identifier, request.url(), request.priority()));
    frame()->loader().progress().willStartLoading(identifier);
    prepareRequest(identifier, request, ResourceResponse());

    if (!m_documentLoader || m_documentLoader->fetcher()->archive() || !request.url().isValid())
        return;
    if (type == Resource::MainResource)
        m_documentLoader->applicationCacheHost()->willStartLoadingMainResource(request);
    else
        m_documentLoader->applicationCacheHost()->willStartLoadingResource(request);
}
uint32_t NTPClient::getEpochTime(const char* host, int port, unsigned long timeout)
{
    if (host == NULL || port < 1) {
        return (uint32_t)-1;
    }

    prepareRequest();
    sendRequest(host, port);

    if (!receiveResponse(timeout)) {
        return (uint32_t)-1;
    }

    return parseResponse();
}
bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, const String& data, int& payloadLength)
{
    ResourceRequest request(beaconURL);
    prepareRequest(frame, request);

    RefPtr<FormData> entityBody = FormData::create(data.utf8());
    unsigned long long entitySize = entityBody->sizeInBytes();
    if (allowance > 0 && static_cast<unsigned>(allowance) < entitySize)
        return false;

    request.setHTTPBody(entityBody);
    request.setHTTPContentType("text/plain;charset=UTF-8");

    issueRequest(frame, request);
    payloadLength = entitySize;
    return true;
}
Exemple #24
0
/**
 * Loads Server information.
 *
 * @brief ServerInfoClient::loadServerInfo
 */
bool ServerInfoClient::loadServerInfo(){
    QString url = baseURL();

    QUrl _url(url);
    QNetworkRequest request( _url );

    prepareRequest(request);
    request.setRawHeader(QByteArray("accept"), QByteArray("application/json"));

    QEventLoop loop;

    QTimer timeoutTimer;
    timeoutTimer.setSingleShot(true);
    connect(&timeoutTimer, SIGNAL(timeout()), &loop, SLOT(quit()));

    //REST request
    QNetworkReply *reply = manager->get( request );
    QObject::connect(reply, SIGNAL(readyRead()), &loop, SLOT(quit()));

    //Wait 2000 miliseconds
    timeoutTimer.start(2000);

    loop.exec();

    if(reply->bytesAvailable() == 0)
    {        
        return false;
    }

    QByteArray arr = reply->readAll();

    QJsonDocument jsonResponse = QJsonDocument::fromJson(arr);
    QJsonObject jsonObject = jsonResponse.object();

    _initializeDate = jsonObject["initializeDate"].toString().toLongLong();
    _serverBootTime = jsonObject["serverBootTime"].toString().toLongLong();
    _currentServerTime = jsonObject["currentServerTime"].toString().toLongLong();
    _icatEnabled = jsonObject["icatEnabled"].toString();
    _relVersion =  jsonObject["relVersion"].toString();
    _apiVersion =  jsonObject["apiVersion"].toString();
    _rodsZone =  jsonObject["rodsZone"].toString();

    return true;

}
void SeafileApiClient::post(const QUrl& url, const QByteArray& data, bool is_put)
{
    body_ = data;
    QNetworkRequest request(url);
    prepareRequest(&request);

    request.setHeader(QNetworkRequest::ContentTypeHeader, kContentTypeForm);

    if (is_put)
        reply_ = na_mgr_->put(request, body_);
    else
        reply_ = na_mgr_->post(request, body_);

    connect(reply_, SIGNAL(finished()), this, SLOT(httpRequestFinished()));

    connect(reply_, SIGNAL(sslErrors(const QList<QSslError>&)),
            this, SLOT(onSslErrors(const QList<QSslError>&)));
}
Exemple #26
0
void RpcClientImpl::call(IComposer& r, IRemoteProcedure& method, IDecomposer** argv, unsigned argc)
{
    _proc = &method;

    prepareRequest(_proc->name(), argv, argc);

    if (!_socket.isConnected())
        _socket.connect(_addr, _port);

    try
    {
        _stream.flush();

        _scanner.begin(_deserializer, r);

        char ch;
        while (_stream.get(ch))
        {
            if (_scanner.advance(ch))
            {
                _proc = 0;
                _scanner.checkException();
                break;
            }
        }
    }
    catch (const RemoteException&)
    {
        throw;
    }
    catch (const std::exception& e)
    {
        cancel();
        throw;
    }

    _proc = 0;

    if (!_stream)
    {
        cancel();
        throw std::runtime_error("reading result failed");
    }
}
bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtrWillBeRawPtr<DOMFormData>& data, int& payloadLength)
{
    ASSERT(data);
    ResourceRequest request(beaconURL);
    prepareRequest(frame, request);

    RefPtr<FormData> entityBody = data->createMultiPartFormData();

    unsigned long long entitySize = entityBody->sizeInBytes();
    if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize)
        return false;

    AtomicString contentType = AtomicString("multipart/form-data; boundary=", AtomicString::ConstructFromLiteral) + entityBody->boundary().data();
    request.setHTTPBody(entityBody.release());
    request.setHTTPContentType(contentType);

    issueRequest(frame, request);
    payloadLength = entitySize;
    return true;
}
bool BeaconLoader::sendBeacon(LocalFrame* frame, int allowance, const KURL& beaconURL, PassRefPtr<ArrayBufferView>& data, int& payloadLength)
{
    ASSERT(data);
    unsigned long long entitySize = data->byteLength();
    if (allowance > 0 && static_cast<unsigned long long>(allowance) < entitySize)
        return false;

    ResourceRequest request(beaconURL);
    prepareRequest(frame, request);

    RefPtr<FormData> entityBody = FormData::create(data->baseAddress(), data->byteLength());
    request.setHTTPBody(entityBody.release());

    // FIXME: a reasonable choice, but not in the spec; should it give a default?
    AtomicString contentType = AtomicString("application/octet-stream");
    request.setHTTPContentType(contentType);

    issueRequest(frame, request);
    payloadLength = entitySize;
    return true;
}
/**
 * Performs a request with a do Delete operation.
 *
 * @brief AbstractHTTPClient::doDelete Delete operation
 * @param url a string that represents the do Delete operation
 * @return returns a QByteArray.
 */
QByteArray AbstractHTTPClient::doDelete(QString &url) {
    QUrl _url(url);
    QNetworkRequest request( _url );

    prepareRequest(request);

    QNetworkReply *reply = manager->deleteResource(request);
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));

    QTimer timeoutTimer;
    timeoutTimer.setSingleShot(true);
    connect(&timeoutTimer, SIGNAL(timeout()), &loop, SLOT(quit()));

    timeoutTimer.start(2000);

    loop.exec();

    QByteArray arr = reply->readAll();
    return arr;
}
Exemple #30
0
// returns true when the processing of a queue has been done
bool QHttpNetworkConnectionPrivate::fillPipeline(QList<HttpMessagePair> &queue, QHttpNetworkConnectionChannel &channel)
{
    if (queue.isEmpty())
        return true;

    for (int i = queue.count() - 1; i >= 0; --i) {
        HttpMessagePair messagePair = queue.at(i);
        const QHttpNetworkRequest &request = messagePair.first;

        // we currently do not support pipelining if HTTP authentication is used
        if (!request.url().userInfo().isEmpty())
            continue;

        // take only GET requests
        if (request.operation() != QHttpNetworkRequest::Get)
            continue;

        if (!request.isPipeliningAllowed())
            continue;

        // remove it from the queue
        queue.takeAt(i);
        // we modify the queue we iterate over here, but since we return from the function
        // afterwards this is fine.

        // actually send it
        if (!messagePair.second->d_func()->requestIsPrepared)
            prepareRequest(messagePair);
        channel.pipelineInto(messagePair);

        // return false because we processed something and need to process again
        return false;
    }

    // return true, the queue has been processed and not changed
    return true;
}