Given a Method, URL, Headers, and Body, perform and HTTP
        request, and return a 3-tuple containing the response status,
        response headers (as httplib.HTTPMessage), and response body.
554224
def _request(self, method, uri, headers={}, body='', stream=False):
        
        response = None
        headers.setdefault('Accept',
                           'multipart/mixed, application/json, */*;q=0.5')

        if self._client._credentials:
            self._security_auth_headers(self._client._credentials.username,
                                        self._client._credentials.password,
                                        headers)

        try:
            self._connection.request(method, uri, body, headers)
            try:
                response = self._connection.getresponse(buffering=True)
            except TypeError:
                response = self._connection.getresponse()

            if stream:
                # The caller is responsible for fully reading the
                # response and closing it when streaming.
                response_body = response
            else:
                response_body = response.read()
        finally:
            if response and not stream:
                response.close()

        return response.status, response.msg, response_body
976908
function(method, url, body, onsuccess, onfail) {
    _method = method;
    _url = url;
    _body = body;
    on('success', onsuccess);
    on('fail', onfail);
    return _request();
  }
1055420
def request(self, method, resource, params=None):
        

        url = self.get_url(resource, params)

        # headers

        headers = {
            'Content-Type': 'application/json'
        }

        auth = requests.auth.HTTPBasicAuth(self.username, self.password)

        # request

        log.info('Request to %s. Data: %s' % (url, params))

        response = requests.request(method, url, data=json.dumps(params), headers=headers, auth=auth)
        response.raise_for_status()

        # response

        log.info('Response from %s: %s' % (url, response.text))
        content = response.json()

        self.parse_status(content.get('status'))

        return content
682113
def log_request_success(self, method, full_url, path, body, status_code, response, duration):
        

        if body and not isinstance(body, dict):
            body = body.decode('utf-8')

        logger.info(
            '%s %s [status:%s request:%.3fs]', method, full_url,
            status_code, duration
        )
        logger.debug('> %s', body)
        logger.debug('< %s', response)

        if tracer.isEnabledFor(logging.INFO):
            if self.url_prefix:
                path = path.replace(self.url_prefix, '', 1)
            tracer.info("curl -X%s 'http://localhost:8047%s' -d '%s'", method, path,
                        self._pretty_json(body) if body else '')

        if tracer.isEnabledFor(logging.DEBUG):
            tracer.debug('#[%s] (%.3fs)\n#%s', status_code, duration,
                         self._pretty_json(response).replace('\n', '\n#') if response else '')
479404
def request(self, method, url, *args):
        
        return self.http.request(method, url, *args)
919933
def html(body, status=200, headers=None):
    '''
    
    '''
    return HTTPResponse(body, status=status, headers=headers,
                        content_type='text/html; charset=utf-8')
248638
def request(self, url, params={}, headers={}):
        
        # Generate current config. Merge in any given headers
        cur_config = self.config.copy()
        if 'headers' in cur_config:
            cur_config['headers'] = cur_config['headers'].copy()
            cur_config['headers'].update(headers)
        else:
            cur_config['headers'] = headers

        with closing(requests.get(url, params=params, **cur_config)) as response:
            if response.status_code == requests.codes.OK:
                # Prepare the temp file. xml content will be
                # stored in a binary file, json in a textfile.
                if (response.headers.get('Content-Type')
                        and ('json' in response.headers['Content-Type'])):
                    enc, fmode = response.encoding, 'w+t'
                else:
                    enc, fmode = None, 'w+b'
                # Create temp file ensuring 2to3 compatibility
                if str_type == str:  # we are on py3
                    source = STF(
                        max_size=self.max_size, mode=fmode, encoding=enc)
                else:
                    # On py27 we must omit the 'encoding' kwarg
                    source = STF(max_size=self.max_size, mode=fmode)
                for c in response.iter_content(chunk_size=1000000,
                                               decode_unicode=bool(enc)):
                    source.write(c)

            else:
                source = None
            code = int(response.status_code)
            if 400 <= code <= 499:
                raise response.raise_for_status()
            return source, response.url, response.headers, code
547344
def post(self, url, body=None):
        
        response = self.http.post(url,
                                  headers=self.headers,
                                  data=body,
                                  **self.requests_params)

        return self.process(response)
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
601072
def response(status, description, resource=DefaultResource):
    # type: (HTTPStatus, str, Optional[Resource]) -> Callable
    
    def inner(o):
        value = Response(status, description, resource)
        try:
            getattr(o, 'responses').add(value)
        except AttributeError:
            setattr(o, 'responses', {value})
        return o
    return inner
647173
def request(self, method, url, **kwargs):
        

        if "data" in kwargs:
            kwargs["data"] = json.dumps(kwargs["data"])

        kwargs["headers"] = {
            'Content-Type': 'application/json',
            'Authorization': 'token %s' % self.__token__,
        }
        req = make_request(
            method,
            url,
            **kwargs
        )
        self.logger.debug(
            "Request::{}::{}".format(method, url),
            extra={
                "request": kwargs,
                "response": {"headers": req.headers, "code": req.status_code, "data": req.content}
            }
        )
        return req
566108
def text(
    body, status=200, headers=None, content_type="text/plain; charset=utf-8"
):
    
    return HTTPResponse(
        body, status=status, headers=headers, content_type=content_type
    )
286851
def fetch(self, url, body=None, headers=None):
        
        if body:
            method = 'POST'
        else:
            method = 'GET'

        if headers is None:
            headers = {}

        # httplib2 doesn't check to make sure that the URL's scheme is
        # 'http' so we do it here.
        if not (url.startswith('http://') or url.startswith('https://')):
            raise ValueError('URL is not a HTTP URL: %r' % (url,))

        httplib2_response, content = self.httplib2.request(
            url, method, body=body, headers=headers)

        # Translate the httplib2 response to our HTTP response abstraction

        # When a 400 is returned, there is no "content-location"
        # header set. This seems like a bug to me. I can't think of a
        # case where we really care about the final URL when it is an
        # error response, but being careful about it can't hurt.
        try:
            final_url = httplib2_response['content-location']
        except KeyError:
            # We're assuming that no redirects occurred
            assert not httplib2_response.previous

            # And this should never happen for a successful response
            assert httplib2_response.status != 200
            final_url = url

        return HTTPResponse(
            body=content,
            final_url=final_url,
            headers=dict(httplib2_response.items()),
            status=httplib2_response.status,
            )
75494
def decode_response(status: int, headers: MutableMapping, body: bytes) -> dict:
    
    data = decode_body(headers, body)
    raise_for_status(status, headers, data)
    raise_for_api_error(headers, data)

    return data
1154328
protected <T> T performCustomRequest(String url, Object requestPayLoad, Class<T> returnType, Map<String, String> uriVariables,
                                       HttpMethod httpMethod, HttpHeaders headers) {

        if (headers == null) {
            headers = new HttpHeaders();
        }

        HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestPayLoad, headers);

        int tryNumber = 1;
        while(tryNumber <= API_RETRY) {
            try {
                ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, returnType, uriVariables);
                return responseEntity.getBody();
            } catch (HttpStatusCodeException error) {
                boolean isTooManyRequestsError = handleHttpStatusCodeError(uriVariables, tryNumber, error);
                if (isTooManyRequestsError) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        log.error("Error in performCustomRequest", e);
                    }
                } else {
                    tryNumber++;
                }
            } catch (RuntimeException e) {
                handleApiError(tryNumber, e);
                tryNumber++;
            }
        }

        throw new RestApiException("Error posting " + returnType.getSimpleName() + " url variables " + uriVariables.toString());
    }
423607
def _request_api(self, **kwargs):
        
        _url = kwargs.get('url')
        _method = kwargs.get('method', 'GET')
        _status = kwargs.get('status', 200)

        counter = 0
        if _method not in ['GET', 'POST']:
            raise ValueError('Method is not GET or POST')

        while True:
            try:
                res = REQ[_method](_url, cookies=self._cookie)
                if res.status_code == _status:
                    break
                else:
                    raise BadStatusException(res.content)
            except requests.exceptions.BaseHTTPError:
                if counter < self._retries:
                    counter += 1
                    continue
                raise MaxRetryError
        self._last_result = res
        return res
533658
def request(method='GET'):
    

    def decorator(func):
        @functools.wraps(func)
        def action(self, *args, **kwargs):
            f = furl(self.server)
            path, body = func(self, *args, **kwargs)

            # deal with query string
            query = dict()
            if isinstance(path, tuple):
                path, query = path
            f.path.add(path)
            f.query.set(query)

            status_code, result = send_rest(f.url, method=method.upper(),
                                            body=body,
                                            session=self.session,
                                            headers=self.headers)
            if status_code != httplib.OK:
                self.logger.error("{impl} {url} headers: {headers}, code: {code}".format(
                    impl=method, url=f.url, headers=self.headers, code=status_code))
            return status_code, result

        return action

    return decorator