Prepare the HTTP handler, URL, and HTTP headers for all subsequent requests
12693
def init(self):
        """"""
        self.debug('Initializing %r', self)
        proto = self.server.split('://')[0]

        if proto == 'https':
            if hasattr(ssl, 'create_default_context'):
                context = ssl.create_default_context()

                if self.ssl_verify:
                    context.check_hostname = True
                    context.verify_mode = ssl.CERT_REQUIRED
                else:
                    context.check_hostname = False
                    context.verify_mode = ssl.CERT_NONE

                self._http_handler = urllib2.HTTPSHandler(debuglevel=0, context=context)
            else:
                self._http_handler = urllib2.HTTPSHandler(debuglevel=0)
        elif proto == 'http':
            self._http_handler = urllib2.HTTPHandler(debuglevel=0)
        else:
            raise ValueError('Invalid protocol %s' % proto)

        self._api_url = self.server + '/api_jsonrpc.php'
        self._http_headers = {
            'Content-Type': 'application/json-rpc',
            'User-Agent': 'python/zabbix_api',
        }

        if self.httpuser:
            self.debug('HTTP authentication enabled')
            auth = self.httpuser + ':' + self.httppasswd
            self._http_headers['Authorization'] = 'Basic ' + b64encode(auth.encode('utf-8')).decode('ascii')
900979
def _prepare_batch_request(self):
        
        if len(self._requests) == 0:
            raise ValueError("No deferred requests")

        multi = MIMEMultipart()

        for method, uri, headers, body in self._requests:
            subrequest = MIMEApplicationHTTP(method, uri, headers, body)
            multi.attach(subrequest)

        # The `email` package expects to deal with "native" strings
        if six.PY3:  # pragma: NO COVER  Python3
            buf = io.StringIO()
        else:
            buf = io.BytesIO()
        generator = Generator(buf, False, 0)
        generator.flatten(multi)
        payload = buf.getvalue()

        # Strip off redundant header text
        _, body = payload.split("\n\n", 1)
        return dict(multi._headers), body
438507
private function prepareStateForRequest($http_verb, $method, $url, $timeout)
    {
        $this->last_error = '';

        $this->request_successful = false;

        $this->last_response = array(
            'headers'     => null, // array of details from curl_getinfo()
            'httpHeaders' => null, // array of HTTP headers
            'body'        => null // content of the response
        );

        $this->last_request = array(
            'method'  => $http_verb,
            'path'    => $method,
            'url'     => $url,
            'body'    => '',
            'timeout' => $timeout,
        );

        return $this->last_response;
    }
1043621
function invokeHTTPHandler(handler, args, req, res, done) {
  // inject parsed parameters into request
  req.params = args;
  // call handler with typical HTTP request/response parameters
  let result = handler(req, res);
  // handle results that are not a trusted Promise with Promise.resolve()
  // which also supports other then-ables
  if (result instanceof Promise === false) {
    result = Promise.resolve(result);
  }
  return result.then(() => done()).catch(done);
}
731518
def makeHttpRequest(method, url, payload, headers, retries=MAX_RETRIES, session=None):
    
    retry = -1
    response = None
    while retry < retries:
        retry += 1
        # if this isn't the first retry then we sleep
        if retry > 0:
            snooze = float(retry * retry) / 10.0
            log.info('Sleeping %0.2f seconds for exponential backoff', snooze)
            time.sleep(snooze)

        # Seek payload to start, if it is a file
        if hasattr(payload, 'seek'):
            payload.seek(0)

        log.debug('Making attempt %d', retry)
        try:
            response = makeSingleHttpRequest(method, url, payload, headers, session)
        except requests.exceptions.RequestException as rerr:
            if retry < retries:
                log.warn('Retrying because of: %s' % rerr)
                continue
            # raise a connection exception
            raise rerr
        # Handle non 2xx status code and retry if possible
        try:
            response.raise_for_status()
        except requests.exceptions.RequestException:
            pass
        status = response.status_code
        if 500 <= status and status < 600 and retry < retries:
            if retry < retries:
                log.warn('Retrying because of: %d status' % status)
                continue
            else:
                raise exceptions.TaskclusterRestFailure("Unknown Server Error", superExc=None)
        return response

    # This code-path should be unreachable
    assert False, "Error from last retry should have been raised!"
676910
def prepare(self):
        
        super(SessionRequestHandler, self).prepare()
        result = yield gen.Task(self.start_session)
        LOGGER.debug('Exiting SessionRequestHandler.prepare: %r', result)
502908
protected void initRequest()
  {
    _hostHeader = null;
    _xForwardedHostHeader = null;
    _expect100Continue = false;

    _cookies.clear();

    _contentLengthIn = -1;

    _hasReadStream = false;

    _readEncoding = null;

    //_request = request;
    //_requestFacade = getHttp().createFacade(this);
    
    _startTime = -1;
    _expireTime = -1;
    
    _isUpgrade = false;
    
    _statusCode = 200;
    _statusMessage = "OK";

    _headerKeysOut.clear();
    _headerValuesOut.clear();
    
    _contentTypeOut = null;
    _contentEncodingOut = null;
    _contentLengthOut = -1;

    _footerKeys.clear();
    _footerValues.clear();

    out().start();

    _isHeaderWritten = false;

    _isClosed = false;
    //_serverHeader = http().serverHeader();
    
    _isKeepalive = true;
  }
523747
protected function prepareHeaders()
    {
        if (!isset($this->headers['Content-Length'])) {

            $content_length = strlen($this->data);

            if ($content_length > 0 || $this->method === 'POST' || $this->method === 'PUT') {
                $this->headers['Content-Length'] = $content_length;
            }
        }

        if (isset($this->uri['user']) && !isset($this->headers['Authorization'])) {
            $pass = isset($this->uri['pass']) ? ':' . $this->uri['pass'] : ':';
            $this->headers['Authorization'] = 'Basic ' . base64_encode($this->uri['user'] . $pass);
        }
    }
1010043
protected function preProcess(): void
    {
        Router::process();

        // disable Layout for XmlHttpRequests
        if (Request::isXmlHttpRequest()) {
            $this->layoutFlag = false;
        }

        // switch to JSON response based on Accept header
        if (Request::checkAccept([Request::TYPE_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON) {
            $this->layoutFlag = false;
            Response::setType('JSON');
        }
    }
246574
def sanitize_http_headers(client, event):
    
    # request headers
    try:
        headers = event["context"]["request"]["headers"]
        event["context"]["request"]["headers"] = varmap(_sanitize, headers)
    except (KeyError, TypeError):
        pass

    # response headers
    try:
        headers = event["context"]["response"]["headers"]
        event["context"]["response"]["headers"] = varmap(_sanitize, headers)
    except (KeyError, TypeError):
        pass

    return event
1334348
def prepare(self):
        """"""
        p = PreparedRequest()
        p.prepare(
            method=self.method,
            url=self.url,
            headers=self.headers,
            files=self.files,
            data=self.data,
            params=self.params,
            auth=self.auth,
            cookies=self.cookies,
            hooks=self.hooks,
        )
        return p
245156
function init()
    {
        // initialize curl handle
        $this->ch = curl_init();

        //set various options

        //set error in case http return code bigger than 400
        if ($this->failonerror) {
            curl_setopt($this->ch, CURLOPT_FAILONERROR, true);
        }

        // allow redirects
        curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);

        // use gzip if possible
        curl_setopt($this->ch, CURLOPT_ENCODING, 'gzip, deflate');

        // do not veryfy ssl
        // this is important for windows
        // as well for being able to access pages with non valid cert
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
    }
27292
def _http_call(self, url, method, **kwargs):
        """"""
        logging.debug("Request[{0}]: {1}".format(method, url))
        start_time = datetime.datetime.now()

        logging.debug("Header: {0}".format(kwargs['headers']))
        logging.debug("Params: {0}".format(kwargs['data']))
        response = requests.request(method, url, verify=False, **kwargs)

        duration = datetime.datetime.now() - start_time
        logging.debug("Response[{0:d}]: {1}, Duration: {2}.{3}s.".format(
            response.status_code, response.reason, duration.seconds,
            duration.microseconds))
        return response
7603
def on_headers(self, response, exc=None):
        ''''''

        if response.status_code == 101:
            connection = response.connection
            request = response.request
            handler = request.websocket_handler
            if not handler:
                handler = WS()
            parser = request.client.frame_parser(kind=1)
            consumer = partial(WebSocketClient.create,
                               response, handler, parser)
            connection.upgrade(consumer)
            response.event('post_request').fire()
            websocket = connection.current_consumer()
            response.request_again = lambda r: websocket
891841
def prepare_request(self, *args, **kw):
        
        self.http_request = self.request_class(self.path, *args, **kw)
689347
function handleRequest(providedUrl, req, res) {
  let $
  // Check for the filter parameter
  const filter = req.params.filter || req.query.filter || req.query.search || ''

  // Add name filtering if it is requested
  let url = providedUrl || ''
  if (filter !== '') {
    url += `&Nafn=${filter}`
  }

  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      return res.status(500).json({ error: 'www.island.is refuses to respond or give back data' })
    }

    try {
      $ = cheerio.load(body)
    } catch (exc) {
      return res.status(500).json({ error: 'Could not parse body' })
    }

    const obj = { results: [] }

    // Clear data regarding the acceptance date of the name (not needed)
    $('.dir li i').each(() => {
      $(this).remove()
    })

    // Loop through all the names in the list and add them to our array
    $('.dir li').each(() => {
      const name = $(this).text()
      obj.results.push(name.trim())
    })

    // Return the results as JSON and cache for 24 hours
    return res.cache(86400).json(obj)
  })
}
436474
public function prepareResponse(): void
    {
        // change default HTTP status code
        $this->response->setStatusCode(200);

        // clear default response headers
        $this->response->resetHeaders();

        // add your response headers
        $this->response->setCharset('UTF-8');
        $this->response->setContentType('text/html');
        $this->response->addHeader(
            'X-Some-Header-Example-Name: headerValueExample'
        ); // add some other headers by this example

        // call here your controller to get real response body
        $body = 'This is an example generated in Route <i>' . get_class($this) . '</i> with a fictive Controller.';

        // set body to response as response body
        $this->response->setBody($body);
    }