Prepare HTTP request.

        :param str url: request URL.
        :param str method: request method.
        :param dict headers: request headers.
        :param object data: JSON-encodable object.

        :rtype: httpclient.HTTPRequest
544587
def _prepare_request(self, url, method, headers, data):
        

        request = httpclient.HTTPRequest(
            url=url, method=method, headers=headers, body=data,
            connect_timeout=self._connect_timeout,
            request_timeout=self._request_timeout,
            auth_username=self._username, auth_password=self._password,
            client_cert=self._client_cert, client_key=self._client_key,
            ca_certs=self._ca_certs, validate_cert=self._verify_cert)

        return request
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
803388
public static String doRequestWithUrl(String url, String method, Map<String, String> header, Map<String, String> params, String charset) throws IOException {
    HttpURLConnection conn = null;
    String rsp = null;

    try {
      String ctype = "application/json";
      String query = buildQuery(params, charset);
      try {
        conn = getConnection(buildGetUrl(url, query), method, header, ctype);
      } catch (IOException e) {
        throw e;
      }

      try {
        rsp = getResponseAsString(conn);
      } catch (IOException e) {
        throw e;
      }

    } finally {
      if (conn != null) {
        conn.disconnect();
      }
    }

    return rsp;
  }
332361
def _http(method, url, headers=None, **kw):
    '''
    
    '''
    params = None
    boundary = None
    if method == 'UPLOAD':
        params, boundary = _encode_multipart(**kw)
    else:
        params = _encode_params(**kw)
    http_url = '%s?%s' % (url, params) if method == _HTTP_GET else url
    http_body = None if method == 'GET' else params
    logging.error('%s: %s' % (method, http_url))
    req = urllib2.Request(http_url, data=http_body)
    req.add_header('Accept-Encoding', 'gzip')
    if headers:
        for k, v in headers.iteritems():
            req.add_header(k, v)
    if boundary:
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
    try:
        resp = urllib2.urlopen(req, timeout=5)
        return _read_http_body(resp)
    finally:
        pass
775308
function Request(httpClient, url, method, headers, params, payload) {
    url = urlparse.parse(url, true); // query string parsing
    this.httpClient   = httpClient;
    this.scheme       = url.protocol.substr(0, url.protocol.length - 1);
    this.port         = url.port ? url.port : (this.scheme === 'http' ? 80 : 443);
    this.host         = url.hostname;
    this.method       = method;
    this.path_info    = url.pathname;
    this.query_string = url.query || {};
    this.headers      = headers || {},
    this.params       = params || {};
    this.payload      = payload || null;
    this.headers['host'] = url.hostname;
}
1214415
def request(method, url, headers=None, data=None, session=None):
    
    base_headers = {
        'User-Agent': random_agent()
    }
    if headers is None:
        headers = {}

    base_headers.update(headers)

    if 'Content-Length' in headers:
        del base_headers['Content-Length']

    headers = base_headers
    if session is not None:
        req = session.request
    else:
        req = requests.request

    r = req(method, url, headers=headers, data=data)
    return r
856833
def _request(method, url, session=None, **kwargs):
    
    url = BASE_URL + url

    if session:
        request_func = getattr(session, method)
    else:
        request_func = getattr(requests, method)
    response = request_func(url, **kwargs)
    # raise an exception if request is not successful
    if not response.status_code == requests.codes.ok:
        raise DweepyError('HTTP {0} response'.format(response.status_code))
    response_json = response.json()
    if response_json['this'] == 'failed':
        raise DweepyError(response_json['because'])
    return response_json['with']
1368529
async def _request(
            self,
            method: str,
            url: str,
            *,
            headers: dict = None,
            params: dict = None,
            json: dict = None) -> dict:
        """"""
        if not headers:
            headers = {}

        try:
            async with self._websession.request(method, url, headers=headers,
                                                params=params,
                                                json=json) as resp:
                resp.raise_for_status()
                data = await resp.json(content_type=None)
                return data
        except ClientError as err:
            raise RequestError(
                'Error requesting data from {}: {}'.format(url, err))
919365
def make_api_call(self, method, url, json_params=None):
        

        url = self.BRANCH_BASE_URI+url

        if self.verbose is True:
            print("Making web request: {}".format(url))

        if json_params is not None:
            encoded_params = json.dumps(json_params)
            headers = {'Content-Type': 'application/json'}
        else:
            encoded_params = None
            headers = {}

        if encoded_params is not None and self.verbose is True:
            print("Params: {}".format(encoded_params))

        request = Request(url, encoded_params.encode('utf-8'), headers)
        request.get_method = lambda: method
        response = urlopen(request).read()
        return json.loads(response.decode('utf-8'))
65408
def request(self, url, method="GET", params=None, headers=None):
        
        params = params or {}
        headers = headers or {}

        logger.debug("URL: %s", url)
        logger.debug("Method: %s", method)
        logger.debug("Headers: %s", headers)
        logger.debug("Params: %s", params)
        
        response, content = self.client().request(url, method, headers=headers,
            body=urllib.urlencode(params))
        
        content = smart_unicode(content)

        logger.debug("Status: %s", response['status'])
        logger.debug("Content: %s", content)
        
        if response['status'] != '200':
            raise OAuthError(_(
                u"Invalid status code %s while requesting %s: %s") % (
                    response['status'], url, content))
        
        return content
816519
def post(self, url: str, data: str, expected_status_code=201):
        
        r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT)
        self._check_response(r, expected_status_code)

        return r.json()
782712
def prepare_request(node):
    
    if node.resource.method not in AVAILABLE_METHODS:
        raise UnsupportedHTTPMethodError(node.resource.method)

    def request(data=None, json=None, **kwargs):
        """
            Make request to node's API route with the given keyword arguments
        """
        # validate given query parameters
        for key, value in kwargs.items():
            param = next((p for p in node.resource.query_params if p.name == key), None)
            if not param:
                raise UnsupportedQueryParameter(node.resource.path, key)

            if not match_type(value, param.type):
                raise TypeError(
                    "Resource Query Parameter has type '{0}' but expected type '{1}'".format(
                        value.__class__.__name__, param.type))

        response = requests.request(node.resource.method, node.resource.absolute_uri, params=kwargs,
                                    data=data, json=json)
        return response
    return request
1312673
def request(method:, url_path:, body: nil, params: {}, header_overrides: {})
      spec = body.nil? ? {} : {body_type: :json}
      endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], **spec)
      request_spec = Smartsheet::API::RequestSpec.new(
          header_overrides: header_overrides,
          body: body,
          params: params
      )
      client.make_request(endpoint_spec, request_spec)
    end
671993
def _http_request(url,
                  headers=None,
                  data=None):
    '''
    
    '''
    if not headers:
        headers = _get_headers()
    session = requests.session()
    log.debug('Querying %s', url)
    req = session.post(url,
                       headers=headers,
                       data=salt.utils.json.dumps(data))
    req_body = req.json()
    ret = _default_ret()
    log.debug('Status code: %d', req.status_code)
    log.debug('Response body:')
    log.debug(req_body)
    if req.status_code != 200:
        if req.status_code == 500:
            ret['comment'] = req_body.pop('message', '')
            ret['out'] = req_body
            return ret
        ret.update({
            'comment': req_body.get('error', '')
        })
        return ret
    ret.update({
        'result': True,
        'out': req.json()
    })
    return ret
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
172182
def request( self, url, method='get',
			decode=None, encode=None, data=None,
			headers=None, raise_for=dict(), queue_lines=None ):
		''''''
		if self.debug_requests:
			url_debug = _dump_trunc(url)
			log.debug('HTTP request: {} {} (h: {}, enc: {}, dec: {}, data: {!r})'.format(
				method, url_debug, headers, encode, decode, _dump_trunc(data) ))

		timeout = HTTPTimeout(**self.request_io_timeouts)
		req_headers = {'User-Agent': 'txU1'}

		if data is not None:
			if encode == 'files':
				boundary = os.urandom(16).encode('hex')
				req_headers['Content-Type'] = 'multipart/form-data; boundary={}'.format(boundary)
				data = MultipartDataSender(data, boundary)
				if not callable(headers): yield data.calculate_length()
				else:
					body = io.BytesIO()
					yield data.calculate_length(body)
					headers = headers(url, method, body.getvalue(), 'multipart/form-data')
			else:
				if encode is None:
					if isinstance(data, types.StringTypes): data = io.BytesIO(data)
				elif encode == 'form':
					req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
					data = io.BytesIO(urllib.urlencode(data))
				elif encode == 'json':
					req_headers['Content-Type'] = 'application/json'
					data = io.BytesIO(json.dumps(data))
				else: raise ValueError('Unknown request encoding: {}'.format(encode))
				if callable(headers):
					data.seek(0)
					headers = headers(url, method, data.read(), req_headers.get('Content-Type'))
				data = FileBodyProducer(data)
		elif callable(headers): headers = headers(url, method, '', None)

		# Passed "headers" should be allowed to be modified by body_hash()
		for k, v in (headers or dict()).viewitems():
			req_headers[force_bytes(k)] = force_bytes(v)
		url, method = it.imap(force_bytes, [url, method.lower()])

		if decode == 'json': req_headers.setdefault('Accept', 'application/json')
		elif decode is not None:
			raise ValueError('Unknown response decoding method: {}'.format(decode))

		res_deferred = first_result( timeout,
			self.request_agent.request( method.upper(), url,
				Headers(dict((k,[v]) for k,v in req_headers.viewitems())), data ) )
		code = res_body = None
		try:
			res = yield res_deferred
			code = res.code
			if code == http.NO_CONTENT: defer.returnValue(None)
			if code not in [http.OK, http.CREATED]:
				if self.debug_requests:
					res_body = defer.Deferred()
					res.deliverBody(DataReceiver(res_body, timer=timeout, allow_loss=True))
					res_body = yield first_result(timeout, res_body)
					log.debug('HTTP error response body: {!r}'.format(res_body))
				raise ProtocolError(code, res.phrase)

			res_body = defer.Deferred()
			res.deliverBody(DataReceiver(res_body, timer=timeout))
			res_body = yield first_result(timeout, res_body)

			if self.debug_requests:
				log.debug( 'HTTP request done ({} {}): {} {} {}, body_len: {}'\
					.format(method, url_debug, code, res.phrase, res.version, len(res_body)) )
			defer.returnValue(json.loads(res_body) if decode is not None else res_body)

		except ( timeout.ActivityTimeout, TimeoutError,
				ResponseFailed, RequestNotSent, RequestTransmissionFailed ) as err:
			if isinstance(err, timeout.ActivityTimeout):
				if not res_deferred.called: res_deferred.cancel()
				if res_body and not res_body.called: res_body.cancel()
			if self.debug_requests:
				log.debug(
					'HTTP transport (underlying protocol) error ({} {}): {}'\
					.format(method, url_debug, err.message or repr(err.args)) )
			raise UnderlyingProtocolError(err)

		except ProtocolError as err:
			if self.debug_requests:
				log.debug(
					'HTTP request handling error ({} {}, code: {}): {}'\
					.format(method, url_debug, code, err.message) )
			raise raise_for.get(code, ProtocolError)(code, err.message)

		except RequestGenerationFailed as err:
			err[0][0].raiseException()

		finally: timeout.state_finished()
998716
def post(self, url, headers=None, body=None, kwargs=None):
        
        return self._request(
            method='post',
            url=url,
            headers=headers,
            body=body,
            kwargs=kwargs
        )