Build the request according to: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
977415
private function buildRequest()
	{
		// template example:
		// -----------------
		// {METHOD} {URI} HTTP-{1.0|1.1}CRLF
		// {headers}CRLF
		// CRLF
		// {message-body}
		$method = 'GET';
		$httpVersion = '1.0';
		$headers = '';
		$body = '';
		$page = ( \array_key_exists('path', $this->url) ) ? $this->url[ 'path' ] : '/';
		$options = \stream_context_get_options( $this->context );

		$httpOptions = [];
		if ( \array_key_exists('http', $options) )
		{
			$httpOptions = $options[ 'http' ];
		}
		// Get method verb.
		if ( \array_key_exists('method', $httpOptions) )
		{
			$method = $httpOptions[ 'method' ];
		}
		// Get content body.
		if ( \array_key_exists('content', $httpOptions) )
		{
			$body = $httpOptions[ 'content' ];
		}
		// Get headers.
		if ( \array_key_exists('header', $httpOptions) )
		{
			$headers = $httpOptions[ 'header' ];
		}
		// Get protocol version.
		if ( \array_key_exists('protocol_version', $httpOptions) )
		{
			$httpVersion = $httpOptions[ 'protocol_version' ];
		}
		// When host header was not set using context for \fopen/\file_get_contents functions,
		// you must manually add the Host: header.
		if ( \strpos(strtolower($headers), 'host:') === FALSE )
		{
			$lineBreak = ( \strlen($headers) > 0 ) ? "\r\n" : '';
			$headers = "host: {$this->url['host']}{$lineBreak}{$headers}";
		}
		if ( \array_key_exists('query', $this->url) )
		{
			$page = $page . '?' . $this->url[ 'query' ];
		}
		// Build the request as a string.
		$request = \sprintf(
			"%s %s HTTP/%s\r\n%s\r\n\r\n%s",
			$method,
			$page,
			$httpVersion,
			$headers,
			$body
		);

		return $request;
	}
822569
def build_request(type, uri, options, api_ver)
      case type.downcase.to_sym
      when :get
        request = Net::HTTP::Get.new(uri.request_uri)
      when :post
        request = Net::HTTP::Post.new(uri.request_uri)
      when :put
        request = Net::HTTP::Put.new(uri.request_uri)
      when :patch
        request = Net::HTTP::Patch.new(uri.request_uri)
      when :delete
        request = Net::HTTP::Delete.new(uri.request_uri)
      else
        raise InvalidRequest, "Invalid rest method: #{type}. Valid methods are: get, post, put, patch, delete"
      end

      options['X-API-Version'] ||= api_ver
      options['auth'] ||= @token
      options['Content-Type'] ||= 'application/json'
      options.delete('Content-Type')  if [:none, 'none', nil].include?(options['Content-Type'])
      options.delete('X-API-Version') if [:none, 'none', nil].include?(options['X-API-Version'])
      options.delete('auth')          if [:none, 'none', nil].include?(options['auth'])
      options.each do |key, val|
        if key.to_s.downcase == 'body'
          request.body = val.to_json rescue val
        else
          request[key] = val
        end
      end

      @logger.debug "  Options: #{options}" # Warning: This may include passwords and tokens

      request
    end
1228241
def modify_request(self, request):
        
        filename = URL.build(path=request.match_info['filename'], encoded=True).path
        raw_path = self._directory.joinpath(filename)
        try:
            filepath = raw_path.resolve()
            if not filepath.exists():
                # simulate strict=True for python 3.6 which is not permitted with 3.5
                raise FileNotFoundError()
        except FileNotFoundError:
            try:
                html_file = raw_path.with_name(raw_path.name + '.html').resolve().relative_to(self._directory)
            except (FileNotFoundError, ValueError):
                pass
            else:
                request.match_info['filename'] = str(html_file)
        else:
            if filepath.is_dir():
                index_file = filepath / 'index.html'
                if index_file.exists():
                    try:
                        request.match_info['filename'] = str(index_file.relative_to(self._directory))
                    except ValueError:
                        # path is not not relative to self._directory
                        pass
127751
function buildRtbRequest(imps, auctionId, gdprConsent, refInfo) {
  let req = {
    'id': auctionId,
    'imp': imps,
    'site': createSite(refInfo),
    'at': 1,
    'device': {
      'ip': 'caller',
      'ua': 'caller',
      'js': 1,
      'language': getLanguage()
    },
    'ext': {
      'adk_usersync': 1
    }
  };
  if (utils.getDNT()) {
    req.device.dnt = 1;
  }
  if (gdprConsent && gdprConsent.gdprApplies !== undefined) {
    req.regs = {ext: {gdpr: Number(gdprConsent.gdprApplies)}};
  }
  if (gdprConsent && gdprConsent.consentString !== undefined) {
    req.user = {ext: {consent: gdprConsent.consentString}};
  }
  return req;
}
352054
def request(self, url, method="GET", params=None, headers=None, is_signed=True):
        
        params = params or {}
        headers = headers or {}
        
        if is_signed:
            params.update(self.get_signing_params())
        
        if method.upper() == "GET":
            url = '%s?%s' % (url, urllib.urlencode(params))
            return self.client().request(url, method=method, headers=headers)
        return self.client().request(url, method, body=urllib.urlencode(params), headers=headers)
720827
function buildRequest(args) {
  const { browser, method } = args;
  const params  = args.params || new Map();
  const site    = /^(https?:|file:)/i.test(browser.site) ? browser.site : `http://${browser.site || 'locahost'}`;
  const url     = URL.resolve(site, URL.format(args.url));

  const headers = new Fetch.Headers(args.headers);

  // HTTP header Referer, but Document property referrer
  const referrer = args.referrer || browser.referrer || browser.referer || args.history.url;
  if (referrer && !headers.has('Referer'))
    headers.set('Referer', referrer);
  if (!headers.has('Accept'))
    headers.set('Accept', 'text/html,*/*');

  if (/^GET|HEAD|DELETE$/i.test(method)) {
    const uri = URL.parse(url, true);
    // These methods use query string parameters instead
    for (let [name, values] of params)
      uri.query[name] = values;
    return new Fetch.Request(URL.format(uri), { method, headers });
  }

  const mimeType = (args.encoding || '').split(';')[0].toLowerCase();
  // Default mime type, but can also be specified in form encoding
  if (mimeType === '' || mimeType === 'application/x-www-form-urlencoded') {
    const urlEncoded = [...params]
      .map(function([name, values]) {
        return values.map(value => `${QS.escape(name)}=${QS.escape(value)}`).join('&');
      })
      .join('&');

    headers.set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
    return new Fetch.Request(url, { method, headers, body: urlEncoded });
  }

  if (mimeType === 'multipart/form-data') {
    const form = new Fetch.FormData();
    for (let [name, values] of params)
      for (let value of values)
        form.append(name, value);
    return new Fetch.Request(url, { method, headers, body: form });
  }

  throw new TypeError(`Unsupported content type ${mimeType}`);
}
1350100
def _build_request(self, method, url, params=None):
        
        full_params = self._get_base_params()
        if params is not None:
            full_params.update(params)
        try:
            request_func = lambda u, d: \
                getattr(self._connector, method.lower())(u, params=d,
                    headers=self._request_headers)
        except AttributeError:
            raise ApiException('Invalid request method')
        # TODO: need to catch a network here and raise as ApiNetworkException

        def do_request():
            logger.debug('Sending %s request "%s" with params: %r',
                method, url, full_params)
            try:
                resp = request_func(url, full_params)
                logger.debug('Received response code: %d', resp.status_code)
            except requests.RequestException as err:
                raise ApiNetworkException(err)

            try:
                resp_json = resp.json()
            except TypeError:
                resp_json = resp.json

            method_returns_list = False
            try:
                resp_json['error']
            except TypeError:
                logger.warn('Api method did not return map: %s', method)
                method_returns_list = True
            except KeyError:
                logger.warn('Api method did not return map with error key: %s', method)

            if method_returns_list is None:
                raise ApiBadResponseException(resp.content)
            elif method_returns_list:
                data = resp_json
            else:
                try:
                    if resp_json['error']:
                        raise ApiError('%s: %s' % (resp_json['code'], resp_json['message']))
                except KeyError:
                    data = resp_json
                else:
                    data = resp_json['data']
                    self._do_post_request_tasks(data)
            self._last_response = resp
            return data
        return do_request
1263699
def create_request(self, method='', url='', query_params=None, body=None, headers=None):
        

        if query_params:
            query = urlencode(query_params)
            if query:
                url = url + ('&' if url.find('?') > 0 else '?') + query

        content_type = None
        accept = None

        if headers is None:
            headers = {}

        it = iterator(headers)

        for key, value in it:
            if key.lower().find('content-type') >= 0:
                content_type = value
            if key.lower().find('accept') >= 0:
                accept = value

        if content_type is None:
            content_type = 'application/json'
            headers['Content-Type'] = content_type

        if accept is None:
            accept = 'application/json'
            headers['Accept'] = accept

        if content_type.lower().find('application/json') >= 0:
            body = json.dumps(body) if body else None
        elif content_type.lower().find('application/x-www-form-urlencoded') >= 0:
            body = urlencode(body) if body else None

        return requests.Request(method, url, headers=headers, data=body)
142729
def _BuildToken(self, request, execution_time):
    """"""
    token = access_control.ACLToken(
        username=request.user,
        reason=request.args.get("reason", ""),
        process="GRRAdminUI",
        expiry=rdfvalue.RDFDatetime.Now() + execution_time)

    for field in ["Remote_Addr", "X-Forwarded-For"]:
      remote_addr = request.headers.get(field, "")
      if remote_addr:
        token.source_ips.append(remote_addr)
    return token
319442
def construct_request_hash
      request = {
        url: url,
        component: component,
        action: action,
        params: params,
        session: session,
        cgi_data: cgi_data,
        sanitizer: request_sanitizer
      }
      request.delete_if {|k,v| config.excluded_request_keys.include?(k) }
      Util::RequestPayload.build(request)
    end
858624
def _get_request(url_root,api_key,path,response_type,params, ssl_verify):
    
    url = _url_builder(url_root,api_key,path,params)
    content = _fetch(url, ssl_verify)
    response = _dispatch(response_type)(content)
    return response
1055391
def request(self, url, method, body=None, headers=None, **kwargs):
        """"""

        content_type = kwargs.pop('content_type', None) or 'application/json'
        headers = headers or {}
        headers.setdefault('Accept', content_type)

        if body:
            headers.setdefault('Content-Type', content_type)

        headers['User-Agent'] = self.USER_AGENT

        resp = requests.request(
            method,
            url,
            data=body,
            headers=headers,
            verify=self.verify_cert,
            timeout=self.timeout,
            **kwargs)

        return resp, resp.text
72333
protected function createHttpRequest()
	{
		$protocol = (isset($_SERVER['HTTPS']) === true && $_SERVER['HTTPS'] === 'on') ? HttpRequest::PROTOCOL_HTTPS : HttpRequest::PROTOCOL_HTTP;
		$uri = StringUtils::startsWith($_SERVER['REQUEST_URI'], '/index.php')?StringUtils::afterFirst($_SERVER['REQUEST_URI'], '/index.php'):$_SERVER['REQUEST_URI'];

		$subFolder = StringUtils::afterFirst(getcwd(), $_SERVER['DOCUMENT_ROOT']);
		$cleanPath = StringUtils::between($uri, $subFolder, '?');

		$languages = array();
		$langsRates = explode(',', isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null);

		foreach($langsRates as $lr) {
			$lrParts = explode(';', $lr);

			$languages[$lrParts[0]] = isset($lrParts[1])?(float)StringUtils::afterFirst($lrParts[1], 'q='):1.0;
		}

		$requestTime = new \DateTime();
		$requestTime->setTimestamp($_SERVER['REQUEST_TIME']);

		$httpRequest = new HttpRequest();

		$httpRequest->setHost($_SERVER['SERVER_NAME']);
		$httpRequest->setPath($cleanPath);
		$httpRequest->setPort($_SERVER['SERVER_PORT']);
		$httpRequest->setProtocol($protocol);
		$httpRequest->setQuery($_SERVER['QUERY_STRING']);
		$httpRequest->setURI($uri);

		$httpRequest->setRequestTime($requestTime);
		$httpRequest->setRequestMethod($_SERVER['REQUEST_METHOD']);
		$httpRequest->setUserAgent(isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null);
		$httpRequest->setLanguages($languages);
		$httpRequest->setAcceptLanguage(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])?$_SERVER['HTTP_ACCEPT_LANGUAGE']:null);
		$httpRequest->setRemoteAddress($_SERVER['REMOTE_ADDR']);
		$httpRequest->setReferrer(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);

		return $httpRequest;
	}
964312
def make_request(parameters):
    
    r = requests.get(bcdata.WFS_URL, params=parameters)
    return r.json()["features"]
119960
function buildRequestor(clientOptions) {
  if(clientOptions.requestor) return clientOptions.requestor;

  var requestorConfig =
    _.pick(clientOptions, 'maxRetryDurationSeconds', 'calcRetryBackoff');

  if(requestorConfig.maxRetryDurationSeconds)
    requestorConfig.maxRetryDurationMillis = requestorConfig.maxRetryDurationSeconds * 1000;

  requestorConfig.logger = buildLogger(clientOptions);

  return require('./lib/utils/httpRequestor.js')
    .create(requestorConfig);
}
1091598
def _build_response(self, resp, is_error=False):
        


        def build(resp):

            response = Response()

            # Pass settings over.
            response.config = self.config

            if resp:

                # Fallback to None if there's no staus_code, for whatever reason.
                response.status_code = getattr(resp, 'status', None)

                # Make headers case-insensitive.
                response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))

                # Start off with our local cookies.
                cookies = self.cookies or dict()

                # Add new cookies from the server.
                if 'set-cookie' in response.headers:
                    cookie_header = response.headers['set-cookie']

                    c = SimpleCookie()
                    c.load(cookie_header)

                    for k,v in c.items():
                        cookies.update({k: v.value})

                # Save cookies in Response.
                response.cookies = cookies

            # Save original resopnse for later.
            response.raw = resp

            if is_error:
                response.error = resp

            response.url = self.full_url

            return response


        history = []

        r = build(resp)
        cookies = self.cookies
        self.cookies.update(r.cookies)

        if r.status_code in REDIRECT_STATI and not self.redirect:

            while (
                ('location' in r.headers) and
                ((r.status_code is codes.see_other) or (self.allow_redirects))
            ):

                if not len(history) < self.config.get('max_redirects'):
                    raise TooManyRedirects()

                history.append(r)

                url = r.headers['location']

                # Handle redirection without scheme (see: RFC 1808 Section 4)
                if url.startswith('//'):
                    parsed_rurl = urlparse(r.url)
                    url = '%s:%s' % (parsed_rurl.scheme, url)

                # Facilitate non-RFC2616-compliant 'location' headers
                # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
                if not urlparse(url).netloc:
                    url = urljoin(r.url, urllib.quote(urllib.unquote(url)))

                # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
                if r.status_code is codes.see_other:
                    method = 'GET'
                else:
                    method = self.method

                # Remove the cookie headers that were sent.
                headers = self.headers
                try:
                    del headers['Cookie']
                except KeyError:
                    pass

                request = Request(
                    url=url,
                    headers=headers,
                    files=self.files,
                    method=method,
                    params=self.session.params,
                    auth=self._auth,
                    cookies=cookies,
                    redirect=True,
                    config=self.config,
                    timeout=self.timeout,
                    _poolmanager=self._poolmanager,
                    proxies = self.proxies,
                )

                request.send()
                cookies.update(request.response.cookies)
                r = request.response
                self.cookies.update(r.cookies)

            r.history = history

        self.response = r
        self.response.request = self
        self.response.cookies.update(self.cookies)
126831
def create_build_from_buildrequest(self, build_request):
        
        build_request.set_openshift_required_version(self.os_conf.get_openshift_required_version())
        build = build_request.render()
        response = self.os.create_build(json.dumps(build))
        build_response = BuildResponse(response.json(), self)
        return build_response