/*
为公有云用户填充http header，传入的request中body&param已经ready
对于DEV用户，则将access_token放到url中
519173
protected void postOperation(AipRequest request) {
        if (isBceKey.get()) {
            // add aipSdk param
            request.addParam("aipSdk", "java");

            String bodyStr = request.getBodyStr();

            try {
                int len = bodyStr.getBytes(request.getContentEncoding()).length;
                request.addHeader(Headers.CONTENT_LENGTH, Integer.toString(len));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            request.addHeader(Headers.CONTENT_MD5, SignUtil.md5(bodyStr, request.getContentEncoding()));

            String timestamp = Util.getCanonicalTime();
            request.addHeader(Headers.HOST, request.getUri().getHost());
            request.addHeader(Headers.BCE_DATE, timestamp);
            request.addHeader(Headers.AUTHORIZATION, CloudAuth.sign(request, this.aipKey, this.aipToken, timestamp));
        }
        else {
            request.addParam("aipSdk", "java");
            request.addParam("access_token", accessToken);
        }
    }
1343034
def get_access_token(self, code, client_id, client_secret):
        ''' 
        
        '''
        headers = {
                'Content-Type' : 'application/json'
                }
        data = {
                'client_id' : client_id,
                'client_secret' : client_secret,
                'code' : code,
                }
        str_data = json.dumps(data)
        response = requests.request(method='POST', url=ACCESS_TOKEN_URL, headers=headers, data=str_data)
        status_code = response.status_code
        if status_code != 200:
            raise ValueError("{} -- {}".format(status_code, response.json()))
        return body['access_token']
419021
function requestWithTokenCheck (defOptions, credentials, token, options, callback) {
  var returnedPromise;
  
  options.headers = options.headers || {};
  extend(true, options, defOptions);
  
  if (Date.now() - token.Timestamp > tokenUpdateTime) {
    returnedPromise = signIn(defOptions, credentials).then(function (data) {
      if (data[0].statusCode !== 200) {
        throw new Error(`${data[0].statusCode}: ${data[0].body.Message}`);
      } else {
        token.AuthenticationToken = data[0].body.AuthenticationToken;
        token.Timestamp = Date.now();
        options.headers.Authorization = `Basic ${token.AuthenticationToken}`;
        return request(options);
      }
    });
  } else {
    options.headers.Authorization = `Basic ${token.AuthenticationToken}`;
    returnedPromise = request(options);
  }
  
  returnedPromise.nodeify(callback);
  return returnedPromise;
}
131036
function(req){
    var token = null;
    if (req.headers && req.headers.authorization) {
      var parts = req.headers.authorization.split(' ');
      if (parts.length === 2){
        var scheme = parts[0];
        var credentials = parts[1];

        if (/^Bearer$/i.test(scheme)){
           token = credentials;
        }
      }
    }else{
      token = this.allParams(req).access_token;
    }
    return token;
  }
529954
def token_of_request(
            self,
            method,
            host,
            url,
            qheaders,
            content_type=None,
            body=None):
        
        parsed_url = urlparse(url)
        netloc = parsed_url.netloc
        path = parsed_url.path
        query = parsed_url.query

        if not host:
            host = netloc

        path_with_query = path
        if query != '':
            path_with_query = ''.join([path_with_query, '?', query])
        data = ''.join(["%s %s" %
                        (method, path_with_query), "\n", "Host: %s" %
                        host, "\n"])

        if content_type:
            data += "Content-Type: %s" % (content_type) + "\n"

        data += qheaders
        data += "\n"

        if content_type and content_type != "application/octet-stream" and body:
            data += body.decode(encoding='UTF-8')

        return '{0}:{1}'.format(self.__access_key, self.__token(data))
637858
function makeHttpRequest(reqHeaders, expectedRes, cacheHitExpected, next) {
  reqHeaders.cookie = _.reduce(reqHeaders.cookie, function(memo, val, name) {
    memo.push(name + '=' + val);
    return memo;
  }, []).join('; ');

  var start = Date.now();

  request({
    url: 'http://localhost:1337',
    method: 'GET',
    headers: reqHeaders
  }, function(err, data, body) {
    var time = Date.now() - start;

    console.log('  status:', data.statusCode);
    console.log('  body  :', body);
    console.log('  time  :', time);

    common.verify(function() {
      JSON.parse(body).should.eql(expectedRes);
      common.shouldUseCache(cacheHitExpected, time);
    });

    next();
  });
}
979904
function RequestBase () {
    // `_baseUrl` and `self` are private variables
    var _baseUrl,
        self = this;

    this.getBaseUrl = function () {
      if (_baseUrl) {
        return _baseUrl;
      }
    };

    this.setBaseUrl = function (baseUrl) {
      _baseUrl = baseUrl;
    };

    /**
     * Checks to make sure the request was a success
     * @param  {Object}  res   A response object
     * @return {Boolean}       A boolean denoting whether the request was a success
     */
    this.isSuccess = function (res) {
      var success = function (status) {
        return status >= 200 && status < 300;
      };
      if (res && success(res.statusCode)) {
        return true;
      }
      return false;
    };

    this.buildOptions = function (path, method, payload) {
      var options,
          accessToken = this.getAccessToken(),
          relayIdentifier = this.getRelayIdentifier(),
          baseUrl = self.getBaseUrl(),
          url = self.constructUrl(baseUrl, path);

      options = {
        uri: url,
        method: method,
        headers: {}
      };

      if (accessToken) {
        options.headers.Authorization = 'Access-Token ' + accessToken;
      } else {
        throw new Error('The required Access Token is missing or malformed');
      }

      if (relayIdentifier) {
        options.headers['Relay-Identifier'] = relayIdentifier;
      }

      if (method && method.toUpperCase() === 'GET') {
        options.qs = payload;
      } else {
        options.json = payload;
      }
      return options;
    };

    this.constructUrl = function (url, path) {
      if (url.slice(-1) === '/' && path.slice(0, 1) === '/') {
        return url.slice(0, -1) + path;
      } else if (url.slice(-1) !== '/' && path.slice(0, 1) !== '/') {
        return url + '/' + path;
      }
      return url + path;
    };

    this.sendRequest = function (path, method, payload) {
      var options = self.buildOptions(path, method, payload),
          reqHandle = request(options).spread(function (response, body) {
            var resp = {},
                responseBody;
            try {
              if (typeof body === 'string') {
                responseBody = JSON.parse(body);
              } else {
                responseBody = body;
              }
            } catch (err) {
              throw new Error('An error occurred parsing the following response from the server: ' + body);
            }
            resp.body = responseBody;
            if (self.isSuccess(response)) {
              resp.getData = function () {
                return resp.body.data;
              };
              resp.isEmpty = function () {
                return Object.getOwnPropertyNames(resp.getData()).length === 0;
              };
              resp.getDataLength = function () {
                var data = resp.getData();
                if (resp.isEmpty()) {
                  return 0;
                } else if (!(data instanceof Array)) {
                  return 1;
                } else {
                  return data.length;
                }
              };
              if (method === 'GET' && resp.body.paging) {
                var pageSize, thisPage, prevPage, nextPage, pageFunc;
                pageSize = resp.body.paging['per_page'];
                thisPage = resp.body.paging.page;
                prevPage = (thisPage === 1 ? thisPage : thisPage - 1);
                nextPage = thisPage + 1;
                pageFunc = function (pageNum) {
                  var _pageNum;
                  _pageNum = pageNum;
                  return function () {
                    payload = (payload === undefined || !payload) ? {} : payload;
                    payload.page = _pageNum;
                    payload['per_page'] = pageSize;
                    return self.sendRequest(path, method, payload);
                  };
                };
                resp.nextPage = pageFunc(nextPage);
                resp.prevPage = pageFunc(prevPage);
              }
              return resp;
            } else {
              throw new error.ApiError(resp);
            }
          });
      return reqHandle;
    };
  }
832408
function APIRequest(method, url) {
	var data, callback, opts, req, headers = messageHeaders(this);
	callback = ( typeof(arguments[2]) === 'function' ? arguments[2] : (data = arguments[2], arguments[3]) );

	if (isNode) {
		opts = URL.parse(url);
		opts.method = method;
		opts.headers = headers;

		req = requesters[opts.protocol.slice(0, -1)].request(opts, function(res) {
			var chunks = [];
			res.on('data', function(c) { chunks[chunks.length] = c; });
			res.once('end', function() {
				chunks = Buffer.concat(chunks);
				Zlib.gunzip(chunks, function(err, uc) {
					if (!err) uc = uc.toString();
					try { res.body = JSON.parse(uc || chunks); } catch(e) {}
					return callback(null, res);
				});
			});
		});
		if (type(data) === 'object' || method.toLowerCase() === 'get') req.setHeader("Content-Type", "application/json; charset=utf-8");
		if (data instanceof Multipart) req.setHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
		if (data) req.write( data.result || JSON.stringify(data), data.result ? 'binary' : 'utf-8' );
		req.end();

		return req.once('error', function(e) { return callback(e.message); });
	}

	req = new XMLHttpRequest();
	req.open(method.toUpperCase(), url, true);
	for (var key in headers) {
		req.setRequestHeader(key, headers[key]);
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			req.statusCode = req.status;
			req.statusMessage = req.statusText;
			try {req.body = JSON.parse(req.responseText);} catch (e) { return handleErrCB(e, callback); }
			callback(null, req);
		}
	};
	if (type(data) === 'object' || method.toLowerCase() === 'get') req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
	if (data instanceof Multipart) req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
	if (data) return req.send( data.result ? data.result : JSON.stringify(data) );
	req.send(null);
}
686784
function RequestDHParams(callback, context) {
    flow.runSeries([
        createPQInnerData,
        encryptPQInnerDataWithRSA,
        requestDHParams,
        decryptDHParams,
        deserializeDHInnerData
    ], callback, context);
}
1262036
private String getAuthTokenFromRequest(HttpServletRequest httpRequest) {
        String authToken = httpRequest.getHeader(AUTH_TOKEN_HEADER_KEY);

        if (authToken == null) {
            // token can also exist as request parameter
            authToken = httpRequest.getParameter(AUTH_TOKEN_PARAMETER_KEY);
        }

        return authToken;
    }
415052
function formatRequest(p, qs) {
		var token = qs.access_token;
		delete qs.access_token;
		p.headers.Authorization = 'Bearer ' + token;

		return true;
	}
864234
def _request(self, url, method = u"get", data = None, headers=None, **kwargs):
        
        #        if self.access_token:
        #            auth_header = {
        #                u"Authorization": "Bearer %s" % (self.access_token)
        #            }
        #            headers.update(auth_header)
        #basic auth
        msg = "method: %s url:%s\nheaders:%s\ndata:%s" % (
            method, url, headers, data)
        #print msg
        if not self.use_oauth:
            auth = (self.sk_user, self.sk_pw)
            if not self.client:
                self.client = requests.session()
            r = self.client.request(method, url, headers=headers, data=data, auth=auth,**kwargs)
        else:
            if not self.client:
                self.client = requests.session(hooks={'pre_request': oauth_hook})
            r = self.client.request(method, url, headers=headers, data=data,**kwargs)
        return r
869438
def build_request_body(header_params, form_params, body)
      # http form
      if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
          header_params['Content-Type'] == 'multipart/form-data'
        data = {}
        form_params.each do |key, value|
          case value
          when ::File, ::Array, nil
            # let typhoeus handle File, Array and nil parameters
            data[key] = value
          else
            data[key] = value.to_s
          end
        end
      elsif body
        data = body.is_a?(String) ? body : body.to_json
      else
        data = nil
      end
      data
    end
579981
protected function requestAccessToken()
    {
        $result = $this->httpGet(self::WECHAT_ACCESS_TOKEN_PREFIX, [
            'corpid' => $this->corpId,
            'corpsecret' => $this->secret
        ]);
        return isset($result['access_token']) ? $result : false;
    }
408688
function httpOk(response,isHead,body) {
  response.setHeader(HTTP_CONTENT_TYPE,MIME_TYPE_JAVASCRIPT);
  response.setHeader(HTTP_CONTENT_LENGTH,body.length);
  response.statusCode = HTTP_OK;
  if (isHead) response.end();
  else response.end(body);
}
1238861
function signRequest(method, url, params, secret){
    //
    // normalize request method
    method = method.toUpperCase();
    if(!(method === 'POST' || method === 'GET')){
        throw new Error('Request method should either Post or Get and you passed "' + method + '"');
    }
    params = params || {};
    //
    // form the parameters string
    var paramStr = '';
    var keys = [];
    for(v in params){
        keys.push(v);
    }
    keys.sort();
    for(var i = 0; i < keys.length; i++){
        paramStr += keys[i] + '=' + params[keys[i]];
    }
    var basicString = method + url + paramStr + secret;
    //console.log('basic string: ' + basicString);
    var encoded = URLEncode(basicString);

    var md5 = crypto.createHash('md5');
    md5.update(encoded);
    var sign = md5.digest('hex');
    var body = '';
    for(v in params){
        body += URLEncode(v) + '=' + URLEncode(params[v]) + '&';
    }
    body += 'sign=' + sign; //append the signature
    return body;
}
869143
function (req, res, next) {
    var accessTokenUrl = 'https://api.login.yahoo.com/oauth2/get_token';
    var clientId = req.body.clientId;
    var clientSecret = config.YAHOO_SECRET;
    var clientSecret64 = new Buffer(clientId + ':' + clientSecret).toString('base64');
    var headers = { Authorization: 'Basic ' + clientSecret64 };
    var formData = {
      code: req.body.code,
      redirect_uri: req.body.redirectUri,
      grant_type: 'authorization_code'
    };

    request.post({ url: accessTokenUrl, form: formData, headers: headers, json: true }, function(err, response, body) {
      if (err) {
        res.status(500).send(err);
        return;
      }
      req.accessToken = body.access_token;
      req.xoauth_yahoo_guid = body.xoauth_yahoo_guid;
      next();
    });
  }