保存后端api配置信息
@param  {Object} ctx  koa 上下文
@param  {String} url  api URL
@param  {Object} data api 数据
@param  {Object} headers 返回头信息
@return {}
559595
function setApiOpt(ctx, url, data, headers) {
    // 保存后端api配置
    ctx.__back__ = ctx.__back__ || {};

    ctx.__back__[url] = {
      url: url,
      data: data,
      headers: headers
    }

    return
  }
394411
function(method, data, callback) {
      xhr.open(method, url, true, user, password);
      if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*");
      if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); });
      if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType);
      if (responseType != null) xhr.responseType = responseType;
      if (timeout > 0) xhr.timeout = timeout;
      if (callback == null && typeof data === "function") callback = data, data = null;
      if (callback != null && callback.length === 1) callback = fixCallback(callback);
      if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); });
      event.call("beforesend", request, xhr);
      xhr.send(data == null ? null : data);
      return request;
    }
1049231
function(data, req, res, servConfig){
        if(!data.cnt) return false;
        // utils.log(utils.chalk.green("----------ajax json:\n", data.type));
        try{
            switch(data.type){
                case 'mjson': //处理mockjson
                    //utils.log(utils.chalk.green(mockjs.mock(JSON.parse(data.cnt))))
                    this.acao && res.setHeader("Access-Control-Allow-Origin","*");
                    data.cnt = JSON.stringify(mockjs.mock(JSON.parse(data.cnt)), null, 4);
                case 'json':
                    this.acao && res.setHeader("Access-Control-Allow-Origin","*");
                    res.writeHead(200, {
                        'Content-Type': utils.MIME['json']
                    });
                    res.write(data.cnt);
                    res.end();
                    break;
                case 'js':
                    //data = new vm.script(data[0]);
                    // 将分解好的url给mock用户*.js 
                    // 只能拦截所起服务下的mock 跨域的不能拦截需用fiddler或charles之类的代理到servermock所起服务下
                    req.parseUrl = req.wwwurl = url.parse(servConfig.protocol + '://' + req.headers.host + req.url);
                    var qstr = req.wwwurl.query ? qs.parse(req.wwwurl.query) : {},
                        query = {};
                    for(var i in qstr){
                        var $ = /(.+)\[(.+)\]/.exec(i);
                        // utils.log(utils.chalk.green("$: ", $));
                        $ ? (query[$[1]] || (query[$[1]] = {})) && (query[$[1]][$[2]] = qstr[i]):
                            query[i] = qstr[i];  
                    }
                    // utils.log(utils.chalk.green("qstr: ", qstr));
                    //extname === 'html' && utils.log(utils.chalk.green(req, '\n\n\n\n', req.wwwurl))
                    req.queryObj = req.wwwurl.queryObj = query;
                    //utils.log(utils.chalk.green('----------mock js func:\n', data.cnt.toString()));
                    vm.runInThisContext('(' + data.cnt + ')')(req, res, require);
                    break;
                default:
                    utils.log(utils.chalk.yellow("mock 暂只支持.mjson .json .js文件"));
                    res.end("mock 暂只支持.mjson .json .js文件");
            }
        } catch(e){
            utils.log(utils.chalk.red("mock error: "), e);
        }
        return true;
    }
889525
public static String get(String url,
                             Map<String, String> headers,
                             String params) throws IOException {

        // 参数
        if (StringUtil.isNotEmpty(params)) {
            url += "?" + params;
        }

        HttpURLConnection httpUrlConn = httpUrlConn(url);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setRequestMethod(Constant.RequestMethodGet);

        // header
        if (headers != null) {
            header(headers, httpUrlConn);
        }

        httpUrlConn.connect();

        return readIO(httpUrlConn);
    }
471358
public String post(String url, String data, Map<String, String> headers) throws IOException {
    return doHttpTransfer(url, data, headers);
  }
1258875
function body(ctx) {
  if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return;

  var consumeMimes = ctx.operation.spec.consumes ||
    ctx.operation.resource.api.spec.consumes || [];
  var mimes = lodash.intersection(consumeMimes,
    Object.keys(ctx.router.decoder));
  var prefix = describe(ctx);

  if (!mimes.length) {
    debug(prefix + 'body middleware disabled (no consumes)');
    return;
  }

  var env = ctx.operation.resource.api.env;
  var options = validateOptions(ctx.operation, 'form', false);
  var schema = transform.parameters(ctx.operation.spec, 'body');

  if (!schema) {
    debug(prefix + 'body middleware disabled (no schema)');
    return;
  }

  return function(req, res, next) {
    var mime = is(req, mimes);
    var bodyErr;

    if (mime) {
      var body;

      if (req.sf.text) {
        try {
          body = ctx.router.decoder[mime](req.sf.text);
        } catch (err) {
          debug(prefix + 'body decoder failed', err);

          bodyErr = new Error('Decode body failed');
          bodyErr.statusCode = 400;
          bodyErr.parent = err;
          bodyErr.expose = true;

          return next(bodyErr);
        }
      } else if (schema.required) {
        bodyErr = new Error('Body required');
        bodyErr.statusCode = 400;
        bodyErr.expose = true;

        return next(bodyErr);
      } else {
        return next();
      }

      req.sf.body = body;

      if (validate(res, env.validate(schema, { body: body }, options))) {
        next();
      }
    } else if (schema.required) {
      bodyErr = new Error('Body required');
      bodyErr.statusCode = 400;
      bodyErr.expose = true;

      return next(bodyErr);
    } else {
      next();
    }
  };
}
216376
function DataURIScheme_StringToDataURI(str,        // @arg String
                                       mimeType,   // @arg MimeTypeString
                                       callback) { // @arg Function - callback(err:Error|null, String:DataURISchemeString):void
                                                   // @ret void
//{@dev
    $args(DataURIScheme_StringToDataURI, arguments);
//}@dev
    var reader = new FileReader();
    reader.addEventListener("loadend", function() {
        var dataURI = reader.result.replace(";base64,", ";charset=utf-8;base64,");
        // example: data:text/plain;charset=utf-8;base64,YfCgrp9i8J+SqQ==
        //{@dev
        console.info(dataURI);
        //}@dev
        callback(null, dataURI);
    });
    reader.addEventListener("error", function(ev) {
        var err = new Error(ev.target.error.name+": "+ev.target.error.message);
        console.info(err);
        callback(err, "");
    });
    reader.readAsDataURL(new Blob([str], {type: mimeType}));
}
164171
function(xhr, promise, headers, method) {
            // XDR cannot set requestheaders, only XHR:
            if (!xhr._isXDR) {
                console.log(NAME, '_setHeaders');
                var name;
                if ((method!=='POST') && (method!=='PUT')) {
                    // force GET-request to make a request instead of using cache (like IE does):
                    headers['If-Modified-Since'] = 'Wed, 15 Nov 1995 01:00:00 GMT';
                    // header 'Content-Type' should only be set with POST or PUT requests:
                    delete headers[CONTENT_TYPE];
                }
                // set all headers
                for (name in headers) {
                    xhr.setRequestHeader(name, headers[name]);
                }

                // in case of POST or PUT method: always make sure 'Content-Type' is specified
                ((method!=='POST') && (method!=='PUT')) || (headers && (CONTENT_TYPE in headers)) || xhr.setRequestHeader(CONTENT_TYPE, DEF_CONTENT_TYPE_POST);
            }
        }
1155219
function(url, data, type) {
		assert(Login.app, "You must set Login.app = my-app-name-as-registered-with-you-again");
		data.app = Login.app;
		data.withCredentials = true; // let the server know this is a with-credentials call
		data.caller = ""+document.location; // provide some extra info
		// add in local cookie auth
		const cookies = Cookies.get();
		let cbase = cookieBase();
		for(let c in cookies) {			
			if (c.substr(0, cbase.length)===cbase) {
				let cv = Cookies.get(c);
				data[c] = cv;
			}
		}

		return $.ajax({
			dataType: "json", // not really needed but harmless
			url: url,
			data: data,
			type: type || 'GET',
			xhrFields: {withCredentials: true}
		});
	}
506567
function ( params, cache ) {
            var sp = ( this._path.indexOf('?') < 0 )? '?' : '&',
                url = ( cache )? this._path : this._path + sp + 'requestTime=' + new Date().getTime();
    
            //URI encode
            if ( params ) {
                var datas = params.split( '&' ),
                    paramNum = datas.length,
                    dataSet, i;
    
                params = '';
                for ( i = 0; i < paramNum; ++i ) {
                    dataSet = datas[i].split( '=' );
                    params += dataSet[0] + '=' + encodeURIComponent( dataSet[1] );
                    if ( i < paramNum - 1 ) params += '&';
                }
            }
    
            this.xhr.onreadystatechange = this._handler;
    
            //GET
            if ( /get/i.test(this._method) ) {
                if ( params && params != '' ) url += '&' + params;
                this.xhr.open( 'GET', url, true );
                this.xhr.send( null );
                //POST
            } else {
                this.xhr.open( 'POST', url, true );
                this.xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded; charset=' + this._charset );
                this.xhr.send( params );
            }
            return this;
        }
1013699
function signedRequestHeaders(apiKey, apiSecretKey, apiUserToken, options) {
  if (!apiKey || !apiSecretKey || !apiUserToken) {
    return false;
  }
  var apiExpDate = Math.floor(Date.now() / 1000) + 600;
  var payload = apiKey + apiUserToken + apiExpDate;
  var hash = CryptoJS.HmacSHA256(payload, apiSecretKey);
  var headers = {
    'x-api-key': apiKey,
    'x-api-user-token': apiUserToken,
    'x-api-signature': 'Method=HMAC-SHA256 Signature=' + hash,
    'x-api-exp-date': apiExpDate,
  };
  return headers;
}
332053
def respond_json(ctx, data, code = None, headers = [], json_dumps_default = None, jsonp = None):
    
    if isinstance(data, collections.Mapping):
        # Remove null properties as recommended by Google JSON Style Guide.
        data = type(data)(
            (name, value)
            for name, value in data.iteritems()
            if value is not None
            )
        error = data.get('error')
        if isinstance(error, collections.Mapping):
            error = data['error'] = type(error)(
                (name, value)
                for name, value in error.iteritems()
                if value is not None
                )
    else:
        error = None
    if jsonp:
        content_type = 'application/javascript; charset=utf-8'
    else:
        content_type = 'application/json; charset=utf-8'
    if error:
        code = code or error['code']
        assert isinstance(code, int)
        response = webob.exc.status_map[code](headers = headers)
        response.content_type = content_type
        if code == 204:  # No content
            return response
        if error.get('code') is None:
            error['code'] = code
        if error.get('message') is None:
            title = errors_title.get(code)
            title = ctx._(title) if title is not None else response.status
            error['message'] = title
    else:
        response = ctx.req.response
        response.content_type = content_type
        if code is not None:
            response.status = code
        response.headers.update(headers)
    # try:
    #     text = json.dumps(data, encoding = 'utf-8', ensure_ascii = False, indent = 2)
    # except UnicodeDecodeError:
    #     text = json.dumps(data, ensure_ascii = True, indent = 2)

    if json_dumps_default is None:
        text = json.dumps(data)
    else:
        text = json.dumps(data, default = json_dumps_default)
    text = unicode(text)
    if jsonp:
        text = u'{0}({1})'.format(jsonp, text)
    response.text = text
    return response
558840
function xhr (url, options, callback) {
  if (typeof options === 'function') {
    callback = options
    options = null
  }
  const o = options || {}
  const req = new XMLHttpRequest()
  const method = o.method || 'get'
  const params = o.data || null

  req.queryString = params
  req.open(method, url, true)
  req.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

  if (method.toLowerCase() === 'post') {
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  }

  for (let key in o.headers) {
    if (o.headers.hasOwnProperty(key)) {
      req.setRequestHeader(key, o.headers[key])
    }
  }

  function stateChange () {
    if (req.readyState === 4) {
      if ((/^[20]/).test(req.status)) {
        callback(null, req.responseText)
      } else if ((/^[45]/).test(req.status)) {
        callback(new Error(req.status))
      }
    }
  }

  req.onreadystatechange = stateChange

  try {
    req.send(params)
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('Error: Resolving URL ' + url)
    callback(e)
  }
}
350715
public static function doCurl($url, $data = null, $header = null, $option = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        // 请求头
        empty($header) || curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        
        // HTTPS
        if (strpos($url, 'https://') !== false) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        
        // 提交数据
        if (! empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, self::transPostFile($data));
        }
        
        // 代理
        if (isset($option['proxy'])) {
            $proxy_config = $option['proxy'];
            curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_PROXY, $proxy_config['host']);
            curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_config['port']);
            isset($proxy_config['user']) && curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_config['user'] . ':' . $proxy_config['passwd']);
        }
        
        // 跳转
        isset($option['location']) && curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $option['location']);
        
        // 超时
        isset($option['timeout']) && curl_setopt($ch, CURLOPT_TIMEOUT, $option['timeout']);
        
        // 头信息
        isset($option['header']) && curl_setopt($ch, CURLOPT_HEADER, $option['header']);
        
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
374654
protected function doRequest($url, $ctx, &$responseHeaders, $methodName) {
        // make a real request
        $result = @file_get_contents($url, null, $ctx);
        if (!$result) {
            throw new \Exception('HTTP request failed', HttpException::REQUEST_FAILED);
        }

        // catch headers
        $responseHeaders = $this->parseHeaders($http_response_header);

        foreach (array('Content-Encoding', 'content-encoding') as $header) {
            if (isset($responseHeaders[$header])) {
                if (strtolower($responseHeaders[$header]) == 'gzip') {
                    $result = gzinflate(substr($result, 10, -8));
                    break;
                }
            }
        }

        $logger = $this->getLogger();
        $logger->debug('Response headers: ' . var_export($responseHeaders, true));
        $logger->debug('Response body: ' . $result);

        // completely failed
        if (!$result && $methodName != 'HEAD') {
            throw new \Exception('No response from server');
        } else if ($responseHeaders['Code'] < 200 || $responseHeaders['Code'] >= 400) {
            // server returned error code

            // decode if it's JSON
            if ($responseHeaders['Content-Type'] == 'application/json') {
                $parsedResult = @json_decode($result, true);
            }

            // pass responses (not) decoded to the adequate exception parameters
            if (isset($parsedResult) && is_array($parsedResult)) {
                $description = $parsedResult['error'];
                if (isset($parsedResult['error_description'])) {
                    $description = $parsedResult['error_description'];
                }
            } else {
                $description = 'Server error occurred';
            }

            throw new HttpException(
                $description,
                $responseHeaders['Code'],
                null,
                $methodName,
                null,
                array(),
                array(),
                array(),
                $result,
                $responseHeaders
            );
        }

        return $result;
    }
161230
function(data) {
    var h, headerArray, headers, i, l, len, o;
    headers = {};
    headerArray = data.getAllResponseHeaders().split('\r');
    for (l = 0, len = headerArray.length; l < len; l++) {
      i = headerArray[l];
      h = i.match(/^([^:]*?):(.*)$/);
      if (!h) {
        h = [];
      }
      h.shift();
      if (h[0] !== void 0 && h[1] !== void 0) {
        headers[h[0].trim()] = h[1].trim();
      }
    }
    o = {};
    o.content = {};
    o.content.data = data.responseText;
    o.headers = headers;
    o.request = {};
    o.request.url = this.invocationUrl;
    o.status = data.status;
    return o;
  }
422158
function finish(requester) {
        var orgHeaders = normal(requester.res.headers);
        // 恢复当前的请求上下文

        var context = requester.ctx;
        if (app.revertContext(context)) {
            // 透传响应头信息
            var res = context.res;
            headers.forEach(function (name) {
                if (orgHeaders[name]) {
                    // 直接覆盖
                    res.set(name, orgHeaders[name]);
                }
            });
        }
        // Dispose
        requester.ctx = context = null;
    }