Request helper function for SendMediaBody & SendChunk.
482992
def __SendMediaRequest(self, request, end):
        """"""
        def CheckResponse(response):
            if response is None:
                # Caller shouldn't call us if the response is None,
                # but handle anyway.
                raise exceptions.RequestError(
                    'Request to url %s did not return a response.' %
                    response.request_url)
        response = http_wrapper.MakeRequest(
            self.bytes_http, request, retry_func=self.retry_func,
            retries=self.num_retries, check_response_func=CheckResponse)
        if response.status_code == http_wrapper.RESUME_INCOMPLETE:
            last_byte = self.__GetLastByte(
                self._GetRangeHeaderFromResponse(response))
            if last_byte + 1 != end:
                self.stream.seek(last_byte + 1)
        return response
1020125
def _send_chunk(self, index, chunk):
        
        self._pending_chunks += 1
        self.outbox.put((index, chunk))
369818
function () {
    return function (req, res, next) {
      var _send = res.send;
      res.send = function (body) {
        var callback = req.params.callback,
            isJSONP  = res.get('Content-Type') === 'application/json' && callback;

        if (body && req.method !== 'HEAD' && isJSONP) {
          res.contentType('js');
          body = callback + '(' + body.toString().trim() + ');';
        }
        _send.call(this, body);
      };
      next();
    };
  }
862974
function send(stream) {
      res.setHeader('content-type', mimetype);

      if (config.setCacheControl && !isNaN(config.maxAge)) {
        res.setHeader('Cache-Control', `public, max-age=${Math.floor(config.maxAge / 1000)}`)
      }

      if (config.beforeSend === 'function') {
        config.beforeSend(res, stream);
      }
      
      stream2buffer(stream, (err, buffer) => {
        if (err) {
          // faild to convert to buffer so lets just stream it.
          res.status(500).send('Internal Server Error');
          return;
        }
        
        const eTag = etag(buffer);
        const headers = req.headers;
        
        if (headers['if-none-match'] && headers['if-none-match'].replace('"', '') === eTag) {
          res.status(304);
          res.setHeader('ETag', eTag);
          res.setHeader('Content-Length', 0);
          res.end();
          return;
        }
        
        res.setHeader('ETag', eTag);

        res.send(buffer);
      });
    }
370558
function sendfile(res, file, options, callback) {
  var done = false;
  var streaming;

  // request aborted
  function onaborted() {
    if (done) return;
    done = true;

    var err = new Error('Request aborted');
    err.code = 'ECONNABORTED';
    callback(err);
  }

  // directory
  function ondirectory() {
    if (done) return;
    done = true;

    var err = new Error('EISDIR, read');
    err.code = 'EISDIR';
    callback(err);
  }

  // errors
  function onerror(err) {
    if (done) return;
    done = true;
    callback(err);
  }

  // ended
  function onend() {
    if (done) return;
    done = true;
    callback();
  }

  // file
  function onfile() {
    streaming = false;
  }

  // finished
  function onfinish(err) {
    if (err && err.code === 'ECONNRESET') return onaborted();
    if (err) return onerror(err);
    if (done) return;

    setImmediate(function () {
      if (streaming !== false && !done) {
        onaborted();
        return;
      }

      if (done) return;
      done = true;
      callback();
    });
  }

  // streaming
  function onstream() {
    streaming = true;
  }

  file.on('directory', ondirectory);
  file.on('end', onend);
  file.on('error', onerror);
  file.on('file', onfile);
  file.on('stream', onstream);
  onFinished(res, onfinish);

  if (options.headers) {
    // set headers on successful transfer
    file.on('headers', function headers(res) {
      var obj = options.headers;
      var keys = Object.keys(obj);

      for (var i = 0; i < keys.length; i++) {
        var k = keys[i];
        res.setHeader(k, obj[k]);
      }
    });
  }

  // pipe
  file.pipe(res);
}
999271
async def _put_chunk(
            cls, session: aiohttp.ClientSession,
            upload_uri: str, buf: bytes):
        """"""
        # Build the correct headers.
        headers = {
            'Content-Type': 'application/octet-stream',
            'Content-Length': '%s' % len(buf),
        }
        credentials = cls._handler.session.credentials
        if credentials is not None:
            utils.sign(upload_uri, headers, credentials)

        # Perform upload of chunk.
        async with await session.put(
                upload_uri, data=buf, headers=headers) as response:
            if response.status != 200:
                content = await response.read()
                request = {
                    "body": buf,
                    "headers": headers,
                    "method": "PUT",
                    "uri": upload_uri,
                }
                raise CallError(request, response, content, None)
1116876
async def send_request(self, params, timeout,
                           type='json_query', command=False):
        """"""
        try:
            with async_timeout.timeout(timeout):
                url = '{url}{type}'.format(
                    url=self._http_url,
                    type=type)
                async with self.websession.get(
                    url=url, params=params,
                        headers=self._headers) as response:
                    if response.status != HTTP_OK:
                        _LOGGER.warning(
                            "Error message %d from Epson.", response.status)
                        return False
                    if command == TURN_ON and self._powering_on:
                        self._powering_on = False
                    if type == 'json_query':
                        return await response.json()
                    return response
        except (aiohttp.ClientError, aiohttp.ClientConnectionError):
            _LOGGER.error("Error request")
            return False
304765
private static String doRequestWithBody(String url, String method, Map<String, String> header, String ctype, byte[] content, int connectTimeout, int readTimeout) throws IOException {
    HttpURLConnection conn = null;
    OutputStream out = null;
    String rsp = null;
    try {
      try {
        conn = getConnection(new URL(url), method, header, ctype);
        conn.setConnectTimeout(connectTimeout);
        conn.setReadTimeout(readTimeout);
      } catch (IOException e) {
        throw e;
      }
      try {
        out = conn.getOutputStream();
        out.write(content);
        rsp = getResponseAsString(conn);
      } catch (IOException e) {
        throw e;
      }

    } finally {
      if (out != null) {
        out.close();
      }
      if (conn != null) {
        conn.disconnect();
      }
    }
    return rsp;
  }
1234131
async def _send_chunk(self, chunk):
        
        self.__log_debug('> %s', chunk)
        await self.__transport._send_data(serialize_packet(
            self._local_port,
            self._remote_port,
            self._remote_verification_tag,
            chunk))
954722
def post(body, path=nil)
      if header["Content-Type"] =~ /application\/(\w+[+])?json/
         chunk_save(path, "POST", body, param, header)
      else
        execute(
          request(path, :post, body, param, header)
        )
      end
    end
494781
async def _send_album(self, entity, files, caption='',
                          progress_callback=None, reply_to=None,
                          parse_mode=(), silent=None):
        """"""
        # We don't care if the user wants to avoid cache, we will use it
        # anyway. Why? The cached version will be exactly the same thing
        # we need to produce right now to send albums (uploadMedia), and
        # cache only makes a difference for documents where the user may
        # want the attributes used on them to change.
        #
        # In theory documents can be sent inside the albums but they appear
        # as different messages (not inside the album), and the logic to set
        # the attributes/avoid cache is already written in .send_file().
        entity = await self.get_input_entity(entity)
        if not utils.is_list_like(caption):
            caption = (caption,)

        captions = []
        for c in reversed(caption):  # Pop from the end (so reverse)
            captions.append(await self._parse_message_text(c or '', parse_mode))

        reply_to = utils.get_message_id(reply_to)

        # Need to upload the media first, but only if they're not cached yet
        media = []
        for file in files:
            # Albums want :tl:`InputMedia` which, in theory, includes
            # :tl:`InputMediaUploadedPhoto`. However using that will
            # make it `raise MediaInvalidError`, so we need to upload
            # it as media and then convert that to :tl:`InputMediaPhoto`.
            fh, fm, _ = await self._file_to_media(file)
            if isinstance(fm, types.InputMediaUploadedPhoto):
                r = await self(functions.messages.UploadMediaRequest(
                    entity, media=fm
                ))
                self.session.cache_file(
                    fh.md5, fh.size, utils.get_input_photo(r.photo))

                fm = utils.get_input_media(r.photo)

            if captions:
                caption, msg_entities = captions.pop()
            else:
                caption, msg_entities = '', None
            media.append(types.InputSingleMedia(
                fm,
                message=caption,
                entities=msg_entities
            ))

        # Now we can construct the multi-media request
        result = await self(functions.messages.SendMultiMediaRequest(
            entity, reply_to_msg_id=reply_to, multi_media=media, silent=silent
        ))

        # We never sent a `random_id` for the messages that resulted from
        # the request so we can't pair them up with the `Updates` that we
        # get from Telegram. However, the sent messages have a photo and
        # the photo IDs match with those we did send.
        #
        # Updates -> {_: message}
        messages = self._get_response_message(None, result, entity)
        # {_: message} -> {photo ID: message}
        messages = {m.photo.id: m for m in messages.values()}
        # Sent photo IDs -> messages
        return [messages[m.media.id.id] for m in media]
1159170
function sendRequest()
  {
    // snow-28673 For s3/blob requests, did not append requestId
    var url = (options.appendRequestId === false) ?
      options.url :
      Util.url.appendParam(options.url, 'httpRequestId', httpRequestId);

    Logger.getInstance().trace(url);

    // build the basic request options
    var requestOptions =
    {
      method             : options.method,
      url                : url,
      headers            : headers,
      gzip               : options.gzip,
      json               : json,
      body               : body,
      timeout            : options.timeout ||
                           this._connectionConfig.getTimeout(),
      requestOCSP        : true,
      rejectUnauthorized : true
    };

    // add the agent and proxy options
    var agentAndProxyOptions = this.getAgentAndProxyOptions(
        url, this._connectionConfig.getProxy());
    requestOptions = Util.apply(requestOptions, agentAndProxyOptions);

    // issue the request
    request = this.getRequestModule()(
        requestOptions, function(err, response, body)
        {
          // if a callback has been specified, normalize the
          // response before passing it to the callback
          if (Util.isFunction(options.callback))
          {
            options.callback(err, normalizeResponse(response), body);
          }
        });
  }
263160
def __ConfigureMultipartRequest(self, http_request):
        """"""
        # This is a multipart/related upload.
        msg_root = mime_multipart.MIMEMultipart('related')
        # msg_root should not write out its own headers
        setattr(msg_root, '_write_headers', lambda self: None)

        # attach the body as one part
        msg = mime_nonmultipart.MIMENonMultipart(
            *http_request.headers['content-type'].split('/'))
        msg.set_payload(http_request.body)
        msg_root.attach(msg)

        # attach the media as the second part
        msg = mime_nonmultipart.MIMENonMultipart(*self.mime_type.split('/'))
        msg['Content-Transfer-Encoding'] = 'binary'
        msg.set_payload(self.stream.read())
        msg_root.attach(msg)

        # NOTE: We encode the body, but can't use
        #       `email.message.Message.as_string` because it prepends
        #       `> ` to `From ` lines.
        fp = six.BytesIO()
        if six.PY3:
            generator_class = MultipartBytesGenerator
        else:
            generator_class = email_generator.Generator
        g = generator_class(fp, mangle_from_=False)
        g.flatten(msg_root, unixfrom=False)
        http_request.body = fp.getvalue()

        multipart_boundary = msg_root.get_boundary()
        http_request.headers['content-type'] = (
            'multipart/related; boundary=%r' % multipart_boundary)
        if isinstance(multipart_boundary, six.text_type):
            multipart_boundary = multipart_boundary.encode('ascii')

        body_components = http_request.body.split(multipart_boundary)
        headers, _, _ = body_components[-2].partition(b'\n\n')
        body_components[-2] = b'\n\n'.join([headers, b'<media body>\n\n--'])
        http_request.loggable_body = multipart_boundary.join(body_components)
1187393
def send_request(id, method, params)
      data = MessagePack.dump([0, id, method, params]).bytes
      ws.send(data)
    rescue => exc
      warn exc
      abort exc
    end
681141
def sendfile(self, data, zlib_compress=None, compress_level=6):
        """"""
        if hasattr(data, 'seek'):
            data.seek(0)

        chunk_size = CHUNK_SIZE

        if zlib_compress:
            chunk_size = BLOCK_SIZE
            compressor = compressobj(compress_level)

        while 1:
            binarydata = data.read(chunk_size)
            if binarydata == '':
                break
            if zlib_compress:
                binarydata = compressor.compress(binarydata)
                if not binarydata:
                    continue
            self.send(binarydata)

        if zlib_compress:
            remaining = compressor.flush()
            while remaining:
                binarydata = remaining[:BLOCK_SIZE]
                remaining = remaining[BLOCK_SIZE:]
                self.send(binarydata)
926036
function hasBody(req) {
  var encoding = 'transfer-encoding' in req.headers;
  var length = 'content-length' in req.headers && req.headers['content-length'] !== '0';
  return encoding || length;
}
1100119
def __ConfigureMediaRequest(self, http_request):
        """"""
        http_request.headers['content-type'] = self.mime_type
        http_request.body = self.stream.read()
        http_request.loggable_body = '<media body>'