-- HTTP REQUESTS ------------------------------------------------------------
11215
function makeRequest(title, cacheHitExpected, next) {
  var start = Date.now();

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

    var receivedImage = new Buffer(body, 'binary');

    console.log(title);
    console.log('  status:', data.statusCode);
    console.log('  sent image length:', IMAGE.length);
    console.log('  received image length  :', receivedImage.length);
    console.log('  time  :', time);
    
    common.verify(function() {
      common.shouldEquals(IMAGE, receivedImage);
    });

    console.log();

    next();
  });
}
539867
function httpRequest(url) {
    var deferred = Q.defer();
    request(url, function(err, response, body) {
      if (err) {
        deferred.reject(new Error(err));
      } else if (!err && response.statusCode !== 200) {
        deferred.reject(new Error(response.statusCode));
      } else {
        deferred.resolve(body);
      }
    });
    return deferred.promise;
  }
324556
function HttpRequest (request, response) {
        this.gateway.Debug(7, "Data=[%s]", request.url);

        var question=url.parse(request.url, true, true);
        var query=question.query;

        var batchRequest = new BatchRequest(this.gateway, query, response);
        var command = path.basename(question.pathname);
        var tracker = true;

        if (query.phonenum == undefined) {
            this.gateway.Debug (0,"Hoops phonenum undefined");
            response.writeHeader(400, {"Content-Type": "text/plain"});
            response.write('ERR: AjaxSMS check-phonenum missing phonenum=xxxxx');
            response.end();
            return;
        }

        switch (command)  {

            case "check-dev-mobile":
                tracker=false;
            case "check-dev-tracker": // http://geotobe.localnet/smsgateway/check-dev-tracker?phonenum=+33782849007&passwd=123456&apn=free&host=46.105.45.122&port=4010
                batchRequest.CheckTrackerBySms(tracker, query);
                break;

            case "send-sms-text":
                batchRequest.SendSmsText(tracker, query);
                break;

            case 'check-accesscode':
                this.backend.getByEmei(batchRequest.CheckAccessCode, query.imeinum);
                break;

            default:
                response.writeHeader(400, {"Content-Type": "text/plain"});
                response.write('ERR: AjaxSMS command: ['+ command + '] in Http Request');
                response.end();
        }

    }
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
46616
function request()
    {
        if (!$this->request) {
            $request = new HttpRequest( new BuildHttpRequest );
            $this->request = $request;
        }

        return $this->request;
    }
750608
function request(
	host,
	method,
	path,
	params,
	query,
	headers,
	options,
	file,
	cb,
	debug
) {
	if (!options) options = {};

	// Remove leading/trailing slash from the path/host so that we can join
	// the two together no matter which way the user chose to provide them.
	if (path[0] === FSLASH) {
		path = path.slice(1);
	}
	if (host[host.length - 1] === FSLASH) {
		host = host.slice(0, host.length - 1);
	}

	var url = host + FSLASH + path;

	var req = superagent[method](url);

	var bar;
	var prev_loaded = 0;
	if (!options.withoutCredentials) req.withCredentials();

	if (!file) {
		// Clean up extra parameters that may have gotten in here
		// if the request came from the CLI module. This is hacky; move elsewhere
		if (params) {
			delete params._;
			delete params.$0;
			req.send(params);
		}
		if (query) {
			delete query._;
			delete query.$0;
			req.query(objectToQueryString(query));
		}
	} else {
		//for file upload params are sent as query params
		req.accept('application/json');
		req.timeout(600000);
		if (query.workspaceFileName && global.paperspace_cli && !query.json) {
			req.on('progress', function _progress(e) {
				if (!bar) bar = new ProgressBar('Uploading ' + node_path.basename(file) + ' [:bar] :rate/bps :percent :etas', {
					complete: '=',
					incomplete: ' ',
					width: 40,
					total: e.total,
				});
				var chunkSize = e.loaded - prev_loaded;
				prev_loaded = e.loaded;
				bar.tick(chunkSize);
			});
		}
		req.attach('file', file);
		delete query._;
		delete query.$0;
		if (query.json) delete query.json;
		req.query(objectToQueryString(query));
	}

	if (headers) {
		for (var headerKey in headers) {
			req.set(headerKey, headers[headerKey]);
		}
	}

	// TODO: Add nicer debug utils? Use the 'debug' module?
	if (debug) {
		console.log(method, url, params, query, headers);
	}

	return req.end(function _requestCallback(err, res) {
		// if content is gzipped, then body is empty object, and content is in 'text'
		var body;
		if (res && res.text) {
			try {
				body = JSON.parse(res.text);
			} catch (parseErr) {
				//console.error(res.text);
				//console.error(parseErr);
				//console.error('res: ' + res)
				//body = {};
				res.body = { message: res.text };
			}
		} else if (res && res.body) { // res.body is expected to be text/json
			body = res.body;
		} else body = {};

		// only return body in callback
		if (cb) return cb(err, body);

		// no callback provided; return the body
		return body;
	});
}
22297
function Ask(server, req, res) {
  this.server = server;
  this.req = req;
  this.res = res;
  this.uri = req.uri;
  this.form = req.form;
  this.path = req.path;
  this.query = req.query;
  this.username = req.username;
  this.password = req.password;
  this.cookies = req.cookies;
}
1199981
function Request(method, url) {
  var self = this;
  this._query = this._query || [];
  this.method = method;
  this.url = url;
  this.header = {}; // preserves header name case
  this._header = {}; // coerces header names to lowercase
  this.on('end', function(){
    var err = null;
    var res = null;

    try {
      res = new Response(self);
    } catch(e) {
      err = new Error('Parser is unable to parse the response');
      err.parse = true;
      err.original = e;
      // issue #675: return the raw response if the response parsing fails
      err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null;
      // issue #876: return the http status code if the response parsing fails
      err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null;
      return self.callback(err);
    }

    self.emit('response', res);

    var new_err;
    try {
      if (res.status < 200 || res.status >= 300) {
        new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
        new_err.original = err;
        new_err.response = res;
        new_err.status = res.status;
      }
    } catch(e) {
      new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android
    }

    // #1000 don't catch errors from the callback to avoid double calling it
    if (new_err) {
      self.callback(new_err, res);
    } else {
      self.callback(null, res);
    }
  });
}
1160240
def http_post_request(url, params, add_to_headers=None, _async=False):
    
    headers = {
        "Accept": "application/json",
        'Content-Type': 'application/json'
    }
    if add_to_headers:
        headers.update(add_to_headers)
    postdata = json.dumps(params)
    if _async:
        response = async_session.post(url, postdata, headers=headers, timeout=10)
        return response
    else:
        response = requests.post(url, postdata, headers=headers, timeout=10)
        try:

            if response.status_code == 200:
                return response.json()
            else:
                logger.debug(f'<POST>error_code:{response.status_code}  reason:{response.reason} detail:{response.text}')
                return
        except BaseException as e:
            logger.exception(
                f'<POST>httpPost failed, detail is:{response.text},{e}')
            return
458857
function request (url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    xhr.open('GET', url)
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.addEventListener('load', _ => {
      try {
        const response = JSON.parse(xhr.response)

        resolve(response)
      } catch (e) {
        reject(e)
      };
    })

    xhr.send(null)
  })
}
125450
function(err, req, res, next) {
    if (err) {
        var url = req.url || '';

        log.debug(req.method, req.headers);
        log.error(('Requested url: ' + url).red, ('Error: ' + err.stack).red);

        if (req.xhr) {
            res.status(500).json({msg: 'Server error'});
        } else {
            res.status(500).send('Server error');
        }
    } else {
        next();
    }
}
1129622
function request(meth, url, headers, query, data, cb) {
    var req = SA(meth, url);
    if (headers) req.set(headers);
    if (query) req.query(query);
    if (data) req.send(data);
    return req.end(function(err, res) {
        if (err) return cb(err);
        return cb(null, res.text);
    });
}
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
541688
function httpNotFound(req, res) {
    console.log(`No request handler found for ${req.url}`);
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.write('404 Not found');
    res.end();
}
668582
function request(requestOptions, callback) {
	var debug = require('debug')('analyze-css:http'),
		fetch = require('node-fetch');

	debug('GET %s', requestOptions.url);
	debug('Options: %j', requestOptions);

	fetch(requestOptions.url, requestOptions).
	then(function(resp) {
		debug('HTTP %d %s', resp.status, resp.statusText);
		debug('Headers: %j', resp.headers._headers);

		if (!resp.ok) {
			var err = new Error('HTTP request failed: ' + (err ? err.toString() : 'received HTTP ' + resp.status + ' ' + resp.statusText));
			callback(err);
		} else {
			return resp.text(); // a promise
		}
	}).
	then(function(body) {
		debug('Received %d bytes of CSS', body.length);
		callback(null, body);
	}).
	catch(function(err) {
		debug(err);
		callback(err);
	});
}
500303
def post(self, url, data, headers=None):
        
        return self._request('POST', url, data, headers=headers)
1229726
private function http_request($url, $cookie, $data = array(), $method = array(), $headers = array()){
        $curl = curl_init();
        if(count($data) && $method == "GET"){
            $data = array_filter($data);
            $url .= "?".http_build_query($data);
            $url = str_replace(array('%5B0%5D'), array('[]'), $url);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (count($headers)){
            $head = array();
            foreach ($headers as $name=>$value){
                $head[] = $name.":".$value;
            }
            curl_setopt($curl, CURLOPT_HTTPHEADER, $head);
        }
        $method = strtoupper($method);
        switch($method) {
            case 'GET':
                break;
            case 'POST':
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
            case 'PUT':
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
            case 'DELETE':
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
        }
        if (!empty($cookie)){
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }