Perform an HTTP request
506454
def request(method, path, options)
      response = connection.send(method) do |request|
        case method
        when :get
          request.url(path, options)
        when :post
          request.path = path
          request.body = options unless options.empty?
        else
          raise Error.new("Unhandled request method #{method}")
        end
      end
      return response.body
    end
839399
async def request(self, method, path, json=None):
        """"""
        url = 'https://{}:{}/api/'.format(self.host, self.port)
        url += path.format(site=self.site)

        try:
            async with self.session.request(method, url, json=json) as res:
                if res.content_type != 'application/json':
                    raise ResponseError(
                        'Invalid content type: {}'.format(res.content_type))
                response = await res.json()
                _raise_on_error(response)
                return response['data']

        except client_exceptions.ClientError as err:
            raise RequestError(
                'Error requesting data from {}: {}'.format(self.host, err)
            ) from None
1345437
def _http_request(self, api, data, headers=None):
        
        if not headers:
            headers = {'Content-Type': 'application/json'}
        if not self._token_valid:
            self._token = self.get_token(self._app_name, self._username, self._password)
        response = requests.post(self._base_url + '/' + api, data=json.dumps(data),
                                 headers=headers)
        # raise an exception if the status was not 200
        logger.debug(json.dumps(data))
        logger.debug(response.text)
        response.raise_for_status()
        return response
280214
def _request(self, url, request_type='GET', **params):
        """"""
        try:
            _LOGGER.debug('Request %s %s', url, params)
            response = self.request(
                request_type, url, timeout=TIMEOUT.seconds, **params)
            response.raise_for_status()
            _LOGGER.debug('Response %s %s %.200s', response.status_code,
                          response.headers['content-type'], response.json())
            response = response.json()
            if 'error' in response:
                raise OSError(response['error'])
            return response
        except OSError as error:
            _LOGGER.warning('Failed request: %s', error)
59472
def _do_request(self, request, url, **kwargs):
        ""
        try:
            response = request(url, stream=True, **kwargs)
        except RequestException as e:
            raise RequestError(e)
        else:
            if response.status_code >= 400:
                raise ResponseError(response)
        # Try to return the response in the most useful fashion given it's
        # type.
        if response.headers.get('content-type') == 'application/json':
            try:
                # Try to decode as JSON
                return response.json()
            except (TypeError, ValueError):
                # If that fails, return the text.
                return response.text
        else:
            # This might be a file, so return it.
            if kwargs.get('params', {}).get('raw', True):
                return response.raw
            else:
                return response
117557
function Request(req, res, url) {
  if (!(this instanceof Request))
    return new Request(req, res, url);

  EventEmitter.call(this);

  this.req = null;
  this.res = null;
  this.socket = null;
  this.method = 'GET';
  this.headers = Object.create(null);
  this.contentType = 'bin';
  this.url = '/';
  this.pathname = '/';
  this.path = [];
  this.trailing = false;
  this.query = Object.create(null);
  this.params = Object.create(null);
  this.body = Object.create(null);
  this.hasBody = false;
  this.username = null;
  this.readable = true;
  this.writable = false;

  if (req)
    this.init(req, res, url);
}
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
860757
def do_request(self, http_verb, url, headers, data=None):
        
        if data:
            data = json.dumps(data)
        request = urllib.request.Request(url, data, headers)
        request.get_method = lambda: http_verb

        try:
            response = urllib.request.urlopen(request)
        except urllib.error.HTTPError as response_:
            response = response_
        except urllib.error.URLError as exception:
            if isinstance(exception.reason, socket.timeout):  # Python 2.6
                self._raise_unrecoverable_error_payplug(exception)
            else:
                self._raise_unrecoverable_error_client(exception)
        except socket.timeout as exception:  # Python 2.7+
            self._raise_unrecoverable_error_payplug(exception)
        except http_client.HTTPException as exception:
            self._raise_unrecoverable_error_client(exception)

        return response.read(), response.code, dict(response.info())
165421
def _do_request(self, method, *args, **kwargs):
        
        log('Doing HTTP [{3}] request: {0} - headers: {1} - payload: {2}'.format(
            args[0], kwargs.get('headers'), kwargs.get('json'), method,),
            level=logging.DEBUG,)
        requests_method = getattr(requests, method)
        return self._handle_response(requests_method(*args, **kwargs))
208668
def __make_request(self, requests_session, method, url, params, data, headers, certificate):
        
        verify = False
        timeout = self.timeout

        try:  # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-546
            response = requests_session.request(method=method,
                                        url=url,
                                        data=data,
                                        headers=headers,
                                        verify=verify,
                                        timeout=timeout,
                                        params=params,
                                        cert=certificate)
        except requests.exceptions.SSLError:
            try:
                response = requests_session.request(method=method,
                                            url=url,
                                            data=data,
                                            headers=headers,
                                            verify=verify,
                                            timeout=timeout,
                                            params=params,
                                            cert=certificate)
            except requests.exceptions.Timeout:
                return self._did_timeout()

        except requests.exceptions.Timeout:
            return self._did_timeout()

        return response
73569
def send_request(self, http_request):
        
        self.request_object = http_request
        self.build_socket()
        self.build_request()
        try:
            self.sock.send(self.request)
        except socket.error as err:
            raise errors.TestError(
                'We were unable to send the request to the socket',
                {
                    'msg': err,
                    'function': 'http.HttpUA.send_request'
                })  			
        finally:
            self.get_response()
948963
function makeHttpRequest(next) {
  var start;

  var httpReq = http.request({
    host: 'localhost',
    port: 1337,
    method: 'POST',
    path: '/upper?page=12',
    headers: {
      'x-to-reverse': 'hello'
    }
  }, function(res) {
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      var time = Date.now() - start;

      var filteredHeaders = _.pick(res.headers, 'x-reversed');
      console.log('FROM HTTP');
      console.log('  status :', res.statusCode);
      console.log('  headers:', JSON.stringify(filteredHeaders));
      console.log('  body   :', body);
      console.log('  time   :', time);

      common.verify(function() {
        filteredHeaders.should.eql({ 'x-reversed': 'olleh' });
        JSON.parse(body).should.eql({ data: 'HELLO-WORLD' });
        common.shouldBeDynamicallyTimed(time);
      });

      console.log();

      next();
    });
  });

  start = Date.now();
  httpReq.end('hello-world');
}
323199
def _make_request(self, path, method='GET', params_=None):
        """"""
        uri = self.api_root + path
        if params_:
            params_['text_format'] = self.response_format
        else:
            params_ = {'text_format': self.response_format}

        # Make the request
        response = None
        try:
            response = self._session.request(method, uri,
                                            timeout=self.timeout,
                                            params=params_)
        except Timeout as e:
            print("Timeout raised and caught:\n{e}".format(e=e))

        # Enforce rate limiting
        time.sleep(max(self._SLEEP_MIN, self.sleep_time))
        return response.json()['response'] if response else None
755232
def request(http_method, uri, options={})
      response = self.class.__send__(http_method, uri, options.merge(basic_auth))
      # Add some logger.debug here ...
      response
    end
192426
def request(self, uri, method, *args, **kwargs):
        
        if self.timeout:
            kwargs["timeout"] = self.timeout
        kwargs["verify"] = self.verify_ssl
        kwargs.setdefault("headers", kwargs.get("headers", {}))
        kwargs["headers"]["User-Agent"] = self.user_agent
        kwargs["headers"]["Accept"] = "application/json"
        if ("body" in kwargs) or ("data" in kwargs):
            if "Content-Type" not in kwargs["headers"]:
                kwargs["headers"]["Content-Type"] = "application/json"
            elif kwargs["headers"]["Content-Type"] is None:
                del kwargs["headers"]["Content-Type"]
        # Allow subclasses to add their own headers
        self._add_custom_headers(kwargs["headers"])
        resp, body = pyrax.http.request(method, uri, *args, **kwargs)
        if resp.status_code >= 400:
            raise exc.from_response(resp, body)
        return resp, body
630657
def do_request(self, http_verb, url, headers, data=None):
        
        if data:
            data = json.dumps(data)
        try:
            response = requests.request(http_verb, url, headers=headers, data=data, verify=config.CACERT_PATH)
        except (requests.exceptions.Timeout, requests.exceptions.TooManyRedirects) as exception:
            self._raise_unrecoverable_error_payplug(exception)
        except requests.exceptions.RequestException as exception:
            self._raise_unrecoverable_error_client(exception)

        return response.content, response.status_code, response.headers
308643
def _do_request(self, method, path, params=None, data=None):
        """"""
        headers = {
            'Content-Type': 'application/json', 'Accept': 'application/json'}

        if self.auth_token:
            headers['Authorization'] = "token={}".format(self.auth_token)

        response = None
        servers = list(self.servers)
        while servers and response is None:
            server = servers.pop(0)
            url = ''.join([server.rstrip('/'), path])
            try:
                response = self.session.request(
                    method, url, params=params, data=data, headers=headers,
                    auth=self.auth, timeout=self.timeout, verify=self.verify)
                marathon.log.info('Got response from %s', server)
            except requests.exceptions.RequestException as e:
                marathon.log.error(
                    'Error while calling %s: %s', url, str(e))

        if response is None:
            raise NoResponseError('No remaining Marathon servers to try')

        if response.status_code >= 500:
            marathon.log.error('Got HTTP {code}: {body}'.format(
                code=response.status_code, body=response.text.encode('utf-8')))
            raise InternalServerError(response)
        elif response.status_code >= 400:
            marathon.log.error('Got HTTP {code}: {body}'.format(
                code=response.status_code, body=response.text.encode('utf-8')))
            if response.status_code == 404:
                raise NotFoundError(response)
            elif response.status_code == 409:
                raise ConflictError(response)
            else:
                raise MarathonHttpError(response)
        elif response.status_code >= 300:
            marathon.log.warn('Got HTTP {code}: {body}'.format(
                code=response.status_code, body=response.text.encode('utf-8')))
        else:
            marathon.log.debug('Got HTTP {code}: {body}'.format(
                code=response.status_code, body=response.text.encode('utf-8')))

        return response