Generates a client-level request by extracting the user parameters (if
430511
private static AmazonWebServiceRequest generateRequest(
            ActionContext context,
            Class<?> type,
            RequestModel model,
            AmazonWebServiceRequest request,
            Object token)
                    throws InstantiationException, IllegalAccessException {

        if (request == null) {
            request = (AmazonWebServiceRequest) type.newInstance();
        }

        request.getRequestClientOptions().appendUserAgent(USER_AGENT);

        for (PathTargetMapping mapping : model.getIdentifierMappings()) {
            Object value = context.getIdentifier(mapping.getSource());
            if (value == null) {
                throw new IllegalStateException(
                        "Action has a mapping for identifier "
                        + mapping.getSource() + ", but the target has no "
                        + "identifier of that name!");
            }
            ReflectionUtils.setByPath(request, value, mapping.getTarget());
        }

        for (PathTargetMapping mapping : model.getAttributeMappings()) {
            Object value = context.getAttribute(mapping.getSource());
            if (value == null) {
                // TODO: Is this ever valid?
                throw new IllegalStateException(
                        "Action has a mapping for attribute "
                        + mapping.getSource() + ", but the target has no "
                        + "attribute of that name!");
            }
            ReflectionUtils.setByPath(request, value, mapping.getTarget());
        }

        for (PathTargetMapping mapping : model.getConstantMappings()) {
            // TODO: This only works for strings; can we do better?
            ReflectionUtils.setByPath(
                    request, mapping.getSource(), mapping.getTarget());
        }

        if (token != null) {
            List<String> tokenPath = model.getTokenPath();
            if (tokenPath == null) {
                throw new IllegalArgumentException(
                        "Cannot pass a token with a null token path");
            }

            ReflectionUtils.setByPath(request, token, tokenPath);
        }

        return request;
    }
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()
1261806
def _get_request_param(self, request):
        """"""
        params = {}
        try:
            params = request.POST.copy()
            if not params:
                params = json.loads(request.body)
        except Exception:
            pass
        for key in params:
            # replace a value to a masked characters
            if key in self.mask_fields:
                params[key] = '*' * 8

        # when a file uploaded (E.g create image)
        files = request.FILES.values()
        if list(files):
            filenames = ', '.join(
                [up_file.name for up_file in files])
            params['file_name'] = filenames

        try:
            return json.dumps(params, ensure_ascii=False)
        except Exception:
            return 'Unserializable Object'
630509
def request(method, path, params=None, data=None, auto_retry=True):
    
    body = None
    if data is not None:
        body = json.dumps(data, cls=utils.DateTimeEncoder)

    headers = {
        'accept': 'application/json',
        'content-type': 'application/json',
        'user-agent': analyzere.user_agent,
    }
    resp = request_raw(method, path, params=params, body=body, headers=headers,
                       auto_retry=auto_retry)
    content = resp.text
    if content:
        try:
            content = json.loads(content, cls=utils.DateTimeDecoder)
        except ValueError:
            raise errors.ServerError('Unable to parse JSON response returned '
                                     'from server.', resp, resp.status_code)
    return content
629321
def _build_request(self, type, commands):
        '''
        
        '''
        request = {}
        headers = {
            'content-type': 'application/json',
        }
        if self.nxargs['connect_over_uds']:
            user = self.nxargs['cookie']
            headers['cookie'] = 'nxapi_auth=' + user + ':local'
            request['url'] = self.NXAPI_UDS_URI_PATH
        else:
            request['url'] = '{transport}://{host}:{port}{uri}'.format(
                transport=self.nxargs['transport'],
                host=self.nxargs['host'],
                port=self.nxargs['port'],
                uri=self.NXAPI_REMOTE_URI_PATH,
            )

        if isinstance(commands, (list, set, tuple)):
            commands = ' ; '.join(commands)
        payload = {}
        payload['ins_api'] = {
            'version': self.NXAPI_VERSION,
            'type': type,
            'chunk': '0',
            'sid': '1',
            'input': commands,
            'output_format': 'json',
        }
        request['headers'] = headers
        request['payload'] = json.dumps(payload)
        request['opts'] = {
            'http_request_timeout': self.nxargs['timeout']
        }
        log.info('request: %s', request)
        return request
1202719
def make_request(name, params=None, version="V001", key=None, api_type="web",
                 fetcher=get_page, base=None, language="en_us"):
    

    params = params or {}
    params["key"] = key or API_KEY
    params["language"] = language

    if not params["key"]:
        raise ValueError("API key not set, please set DOTA2_API_KEY")

    url = url_map("%s%s/%s/" % (base or BASE_URL, name, version), params)
    return fetcher(url)
251244
def make_request(self, method, path, params={}, body="", username=None,
                     password=None, base_uri=None, content_type=None):
        headers = {
            'User-Agent': CreateSend.user_agent,
            'Content-Type': 'application/json; charset=utf-8',
            'Accept-Encoding': 'gzip, deflate'}
        if content_type:
            headers['Content-Type'] = content_type
        parsed_base_uri = urlparse(
            CreateSend.base_uri if not base_uri else base_uri)
        """"""
        if username and password:
            headers['Authorization'] = "Basic %s" % base64.b64encode(
                ("%s:%s" % (username, password)).encode()).decode()
        elif self.auth_details:
            if 'api_key' in self.auth_details and self.auth_details['api_key']:
                headers['Authorization'] = "Basic %s" % base64.b64encode(
                    ("%s:x" % self.auth_details['api_key']).encode()).decode()
            elif 'access_token' in self.auth_details and self.auth_details['access_token']:
                headers['Authorization'] = "Bearer %s" % self.auth_details[
                    'access_token']
        self.headers = headers

        """If in fake web mode (i.e. self.stub_request has been called),
    self.faker should be set, and this request should be treated as a fake."""
        if self.fake_web:
            # Check that the actual url which would be requested matches
            # self.faker.url.
            actual_url = "https://%s%s" % (parsed_base_uri.netloc,
                                           self.build_url(parsed_base_uri, path, params))
            self.faker.actual_url = actual_url

            def same_urls(url_a, url_b):
                a = urlparse(url_a)
                b = urlparse(url_b)
                return (a.scheme == b.scheme and
                        a.netloc == b.netloc and
                        a.path == b.path and
                        a.params == b.params and
                        parse_qs(a.query) == parse_qs(b.query) and
                        a.fragment == b.fragment
                        )
            if not same_urls(self.faker.url, actual_url):
                raise Exception("Faker's expected URL (%s) doesn't match actual URL (%s)" % (
                    self.faker.url, actual_url))

            self.faker.actual_body = body

            def same_bodies(body_a, body_b):
                return json.loads(body_a) == json.loads(body_b)
            if self.faker.body is not None:
                if not same_bodies(self.faker.body, body):
                    raise Exception("Faker's expected body (%s) doesn't match actual body (%s)" % (
                        self.faker.body, body))

            data = self.faker.open() if self.faker else ''
            status = self.faker.status if (
                self.faker and self.faker.status) else 200
            return self.handle_response(status, data)

        c = VerifiedHTTPSConnection(parsed_base_uri.netloc, timeout=self.timeout)
        c.request(method, self.build_url(
            parsed_base_uri, path, params), body, headers)
        response = c.getresponse()
        if response.getheader('content-encoding', '') == 'gzip':
            data = gzip.GzipFile(fileobj=BytesIO(response.read())).read()
        else:
            data = response.read()
        c.close()
        return self.handle_response(response.status, data)
679825
def _request(self, typ, id=0, method='GET', params=None, data=None, url=None):
        

        headers = { "Accept": "application/json" }
        auth = None

        if self.user:
            auth = (self.user, self.password)

        if not url:
            if id:
                url = "%s/%s/%s" % (self.url, typ, id)
            else:
                url = "%s/%s" % (self.url, typ)

        return requests.request(method, url, params=params, data=data, auth=auth, headers=headers)
290823
def json_request(endpoint, verb='GET', session_options=None, **options):
    
    req = functools.partial(_request, endpoint, verb, session_options,
                            json=True, **options)
    return _run_in_fresh_loop(req)
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
235010
function makeRequest(){
  output('Sending the request...');
  var options = {
    method: $method.value,
    headers: {
      Accept: document.getElementById('accept').value
    },
    followRedirect: $followRedirect.checked
  };
  if(options.method === 'POST'){
    options.body = $requestBody.value;
  }
  client.request($url.value, options, function(error, response){
    if(error){
      genericError();
    } else {
      displayResponse(response);
      
      if(response.statusCode === 401){
        $authStatus.classList.remove('loggedin');
        $tokenDisplay.value = '';
        
      } else {
        $authStatus.classList.add('loggedin');
        $tokenDisplay.value = 'Bearer ' + client.getAccessToken();
      }
    }
  });
}
1259194
def _get(self, url,
             param_dict={},
             securityHandler=None,
             additional_headers=[],
             handlers=[],
             proxy_url=None,
             proxy_port=None,
             compress=True,
             custom_handlers=[],
             out_folder=None,
             file_name=None):
        
        self._last_method = "GET"
        CHUNK = 4056
        param_dict, handler, cj = self._processHandler(securityHandler, param_dict)
        headers = [] + additional_headers
        if compress:
            headers.append(('Accept-encoding', 'gzip'))
        else:
            headers.append(('Accept-encoding', ''))
        headers.append(('User-Agent', self.useragent))
        if len(param_dict.keys()) == 0:
            param_dict = None
        if handlers is None:
            handlers = []
        if handler is not None:
            handlers.append(handler)
        handlers.append(RedirectHandler())
        if cj is not None:
            handlers.append(request.HTTPCookieProcessor(cj))
        if proxy_url is not None:
            if proxy_port is None:
                proxy_port = 80
            proxies = {"http":"http://%s:%s" % (proxy_url, proxy_port),
                       "https":"https://%s:%s" % (proxy_url, proxy_port)}
            proxy_support = request.ProxyHandler(proxies)
            handlers.append(proxy_support)
        opener = request.build_opener(*handlers)
        opener.addheaders = headers
        if param_dict is None:
            resp = opener.open(url, data=param_dict)
        elif len(str(urlencode(param_dict))) + len(url) >= 1999:
            resp = opener.open(url, data=urlencode(param_dict))
        else:
            format_url = url + "?%s" % urlencode(param_dict)
            resp = opener.open(fullurl=format_url)
        self._last_code = resp.getcode()
        self._last_url = resp.geturl()
        #  Get some headers from the response
        maintype = self._mainType(resp)
        contentDisposition = resp.headers.get('content-disposition')
        contentEncoding = resp.headers.get('content-encoding')
        contentType = resp.headers.get('content-Type').split(';')[0].lower()
        contentLength = resp.headers.get('content-length')
        if maintype.lower() in ('image',
                                'application/x-zip-compressed') or \
           contentType == 'application/x-zip-compressed' or \
           (contentDisposition is not None and \
           contentDisposition.lower().find('attachment;') > -1):

            fname = self._get_file_name(
                contentDisposition=contentDisposition,
                url=url)
            if out_folder is None:
                out_folder = tempfile.gettempdir()
            if contentLength is not None:
                max_length = int(contentLength)
                if max_length < CHUNK:
                    CHUNK = max_length
            file_name = os.path.join(out_folder, fname)
            with open(file_name, 'wb') as writer:
                for data in self._chunk(response=resp,
                                        size=CHUNK):
                    writer.write(data)
                    writer.flush()
                writer.flush()
                del writer
            return file_name
        else:
            read = ""
            for data in self._chunk(response=resp,
                                    size=CHUNK):
                if self.PY3 == True:
                    read += data.decode('utf-8')
                else:
                    read += data

                del data
            try:
                results = json.loads(read)
                if 'error' in results:
                    if 'message' in results['error']:
                        if results['error']['message'] == 'Request not made over ssl':
                            if url.startswith('http://'):
                                url = url.replace('http://', 'https://')
                                return self._get(url,
                                               param_dict,
                                               securityHandler,
                                               additional_headers,
                                               handlers,
                                               proxy_url,
                                               proxy_port,
                                               compress,
                                               custom_handlers,
                                               out_folder,
                                               file_name)
                return results
            except:
                return read
1166914
function getParams(user, auth, url, options, headers) {
    return _.extend({
        url: url,
        headers: _.extend({
            'User-Agent': user.userAgent,
            'Authorization': getAuthorization(user, auth)
        }, headers)
    }, options);
}
466235
def collect_request_parameters(self, request):
        """"""

        class OAuthParameters(object):
            """Used as a parameter container since plain object()s can't"""
            pass

        # Collect parameters
        query = urlparse(request.url.decode("utf-8")).query
        content_type = request.headers.get('Content-Type', '')
        if request.form:
            body = request.form.to_dict()
        elif content_type == 'application/x-www-form-urlencoded':
            body = request.data.decode("utf-8")
        else:
            body = ''
        headers = dict(encode_params_utf8(request.headers.items()))
        params = dict(collect_parameters(uri_query=query, body=body, headers=headers))

        # Extract params and store for convenient and predictable access
        oauth_params = OAuthParameters()
        oauth_params.client_key = params.get(u'oauth_consumer_key')
        oauth_params.resource_owner_key = params.get(u'oauth_token', None)
        oauth_params.nonce = params.get(u'oauth_nonce')
        oauth_params.timestamp = params.get(u'oauth_timestamp')
        oauth_params.verifier = params.get(u'oauth_verifier', None)
        oauth_params.callback_uri = params.get(u'oauth_callback', None)
        oauth_params.realm = params.get(u'realm', None)
        return oauth_params
682214
function makeApiUrl(options,parameters) {

    var query = parameters;

    //
    // If any parameter given in array, make it string separated by semicolon(;)
    //
    for(let key in query){
        if( _.isArray(query[key]) ){
            query[key] = _.join(query[key],';');
        }
    }

    let curTime = Math.floor(Date.now() / 1000);
    let randomToken = randomstring.generate(6);

    query.time = curTime;
    query.apiKey  = options.API_KEY;

    //
    // Sort parameters according to codeforces API rules
    //
    query = _
        .chain(query)
        .map( (value, key) => {
            return { key, value };
        })
        .orderBy(['key', 'value'], ['desc', 'desc'])
        .reverse()
        .keyBy('key')
        .mapValues('value')
        .value();

    let qsFy = qs.stringify(query,{ encode: false });
    let apiSig = `${randomToken}/${options.method}?${qsFy}#${options.API_SECRET}`;

    apiSig = sha512(apiSig).toString();
    query.apiSig = randomToken + apiSig;
    qsFy = qs.stringify(query,{ encode: false });

    let url = `${options.API_URL}/${options.method}?${qsFy}`;

    return url;
}
362482
def generate_canonical_request(method, parsed_url, headers, signed_headers, content_sha256):
    
    lines = [method, parsed_url.path, parsed_url.query]

    # Headers added to canonical request.
    header_lines = []
    for header in signed_headers:
        value = headers[header.title()]
        value = str(value).strip()
        header_lines.append(header + ':' + str(value))

    lines = lines + header_lines
    lines.append('')

    lines.append(';'.join(signed_headers))
    lines.append(content_sha256)
    return '\n'.join(lines)
450463
function make_request_from_instance(params) {
        const this_endpoint = this;
        const { preparer } = this_endpoint;
        const headers = Object.assign(
            {},
            this_endpoint.headers,
            params.headers,
            ); // eslint-disable-line indent
        return this_endpoint.constructor.make_request(
            Object.assign({}, params, { headers, preparer }),
            compose_url_from_instance.bind(this_endpoint),
            ); // eslint-disable-line indent
    }