Does the magic of actually sending the request and parsing the response
481471
def _make_request(self, request):
        
        # TODO: I'm sure all kinds of error checking needs to go here
        try:
            response_raw = urllib2.urlopen(request)
        except urllib2.HTTPError, e:
            print e.read()
            raise

        response_str = response_raw.read()
        response = json.loads(response_str)

        self._last_request = request
        self._last_response = response_raw
        self._last_response_str = response_str
        return response
59472
def _do_request(self, request, url, **kwargs):
        ""
        try:
            response = request(url, stream=True, **kwargs)
        except RequestException as e:
            raise RequestError(e)
        else:
            if response.status_code >= 400:
                raise ResponseError(response)
        # Try to return the response in the most useful fashion given it's
        # type.
        if response.headers.get('content-type') == 'application/json':
            try:
                # Try to decode as JSON
                return response.json()
            except (TypeError, ValueError):
                # If that fails, return the text.
                return response.text
        else:
            # This might be a file, so return it.
            if kwargs.get('params', {}).get('raw', True):
                return response.raw
            else:
                return response
465187
function (req, res) {
		LOG.warn('handle_request');

		// attach custom res methods (borrowed from express)
		res = UTIL.mixin(res, response);

		LOG.sys('HTTP req received, header', 'SR.REST');
		LOG.sys(req.headers, 'SR.REST');
		
		var content_type = req.headers['content-type'];

		// NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly
		if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) { 
			LOG.warn('parsing form request...', 'SR.REST');
			route(req, res);
			return;
		}
		
		// temp buffer for incoming request
		var data = '';
		var JSONobj = undefined;
		
		req.on('data', function (chunk) {
			data += chunk;
		});

		req.on('end', function () {
			
			var JSONobj = undefined;
			
			try {
				if (data !== '') {
						
					if (content_type.startsWith('application/x-www-form-urlencoded')) {
						JSONobj = qs.parse(data);
					} else if (content_type.startsWith('application/json')) {
						JSONobj = UTIL.convertJSON(decodeURIComponent(data));
					} else if (content_type.startsWith('application/sdp')) {
						JSONobj = data;
					} else {
						var msg = 'content type not known: ' + content_type;
						LOG.warn(msg, 'SR.REST');
						SR.REST.reply(res, msg);
						//res.writeHead(200, {'Content-Type': 'text/plain'});
						//res.end(msg);
						return;
					}
				}
			} catch (e) {
				var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type;
				LOG.error(msg, 'SR.REST');
				//res.writeHead(200, {'Content-Type': 'text/plain'});
				//res.end(msg);
				SR.REST.reply(res, msg);
				return;
			}

			route(req, res, JSONobj);
		})
	}
835248
private function parseResponse() {
        $token = "\n";
        $line = strtok($this->returnedTransfer, $token);

        if (stripos($line, ' 100 Continue') !== false && stripos($line, 'HTTP') === 0) {
            do {
                $line = strtok($token);
            } while (0 < strlen(trim($line)));
            strtok($token); // also slip next HTTP TAG
        }

        while (0 < strlen(trim($line = strtok($token)))) {
            $this->parseResponseHeaderLine($line);
        }
        $this->parsedResponse = strtok("");
    }
955937
def response(request)
      response = responses.fetch(@response_counter, responses.last)
      if response.respond_to?(:call)
        response = response.call(request)
      end
      @response_counter += 1
      response.mock = @from || true
      response
    end
1049614
def _parse_request(self):
        '''
        
        '''
        self.req_method = 'unknown'
        self.req_params = {}
        self.req_rpc_version = '2.0'
        self.req_id = 0
        self.data = self.rfile.read(int(self.headers.get('content-length')))
        data_dict = json.loads(self.data)
        self.req_method = data_dict['method']
        self.req_params = decode_data(data_dict['params'])
        self.req_rpc_version = data_dict['jsonrpc']
        self.req_id = data_dict['id']
816499
function parse_request(){
		parent::parse_request();
		if (isset($_GET["id"]))
			$this->request->set_filter($this->config->id["name"],$_GET["id"],"=");
		else if (!$_POST["ids"])
			throw new Exception("ID parameter is missed");
	}
1120855
def send(url, data):
    
    validate(data)

    return requests.post(url, json=data)
1276295
protected function parse_request() {
        // Retrieve and clean the POST/GET parameters from the parameters specific to the server.
        parent::set_web_service_call_settings();

        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
            $this->username = isset($_GET['wsusername']) ? $_GET['wsusername'] : null;
            $this->password = isset($_GET['wspassword']) ? $_GET['wspassword'] : null;
        } else {
            $this->token = isset($_GET['wstoken']) ? $_GET['wstoken'] : null;
        }

        // Get the XML-RPC request data.
        $rawpostdata = $this->fetch_input_content();
        $methodname = null;

        // Decode the request to get the decoded parameters and the name of the method to be called.
        $decodedparams = xmlrpc_decode_request($rawpostdata, $methodname, 'UTF-8');
        $methodinfo = external_api::external_function_info($methodname);
        $methodparams = array_keys($methodinfo->parameters_desc->keys);
        $methodvariables = [];

        // Add the decoded parameters to the methodvariables array.
        if (is_array($decodedparams)) {
            foreach ($decodedparams as $index => $param) {
                // See MDL-53962 - XML-RPC requests will usually be sent as an array (as in, one with indicies).
                // We need to use a bit of "magic" to add the correct index back. Zend used to do this for us.
                $methodvariables[$methodparams[$index]] = $param;
            }
        }

        $this->functionname = $methodname;
        $this->parameters = $methodvariables;
    }
572932
def perform_api_request(
        self,
        url,
        method='POST',
        headers=None,
        body=None,
        **kwargs
    ):
        '''
        
        '''
        assert method in ('GET', 'POST')
        if method == 'GET':
            response = self._perform_get(url, headers=headers, **kwargs)
        elif method == 'POST':
            response = self._perform_post(url, headers=headers, data=body, **kwargs)
        return response
1185591
def process_response(self, request, response):
        
        process = False

        # Don't do anything for unsecure requests, unless DEBUG is on
        if not self.allow_http and not request.is_secure():
            return response

        if response.status_code == UNAUTHORIZED:
            pass
        elif response.status_code == FOUND:
            location = urllib_parse.urlparse(response['Location'])
            if location.path != settings.LOGIN_URL:
                # If it wasn't a redirect to the login page, we don't touch it.
                return response
            elif not self.is_agent_a_robot(request):
                # We don't touch requests made in order to be shown to humans.
                return response

        realm = getattr(settings, 'BASIC_AUTH_REALM', request.META.get('HTTP_HOST', 'restricted'))
        
        if response.status_code == FOUND:
            response = self.unauthorized_view(request)

        authenticate = response.get('WWW-Authenticate', None)
        if authenticate:
            authenticate = 'Basic realm="%s", %s' % (realm, authenticate)
        else:
            authenticate = 'Basic realm="%s"' % realm
        response['WWW-Authenticate'] = authenticate

        return response
102250
function Request(reqBytes){
  var parsed;
  var err

  try {
    parsed = types.Request.decode(reqBytes);
  } catch (e) {
    err = e;
  }


  //Check for request errors here
  if(err){
    this.BadRequest = true;
    this.errCode = types.CodeType.EncodingError;
    this.errMsg = "The request failed to be decoded"
  } else if(!types.methodLookup[parsed.type]){
    //Request type not recognized
    //Make a request object for the error
    this.BadRequest = true;
    this.errCode = types.CodeType.UnknownRequest;
    this.errMsg = "The request type was not understood"
  } else {

    this.BadRequest = false; 
    this.type = parsed.type;
    this.method = types.methodLookup[this.type];
    this.data = parsed.data.buffer.slice(parsed.data.offset);
    this.dataLength = parsed.data.limit - parsed.data.offset;
    this.dataLittle = parsed.data.littleEndian;
    this.key = parsed.key;
    this.value = parsed.value;
  }
}
276036
def do_POST(self):
        '''
        
        '''
        try:
            self._parse_request()
        except Exception as ex1:
            print(traceback.format_exc())
            self.error_response(JSONRPC_PARSE_ERROR, 'exception when parsing jsonrpc request [%s]' % (ex1))
            return
        try:
            if self.req_method.startswith('_meta_'):
                self.req_method = self.req_method.replace('_meta_', '')
                instance = self.server.meta
            else:
                instance = self.server.impl
            method = getattr(instance, self.req_method)
        except AttributeError:
            self.error_response(JSONRPC_METHOD_NOT_FOUND, 'no method named "%s"' % self.req_method)
            return
        try:
            res = method(**self.req_params)
        except Exception as ex1:
            self.error_response(JSONRPC_INTERNAL_ERROR, 'exception in call "%s(%s)" -> %s' % (self.req_method, self.req_params, ex1))
            return
        if res is None:
            self.error_response(JSONRPC_NO_RESULT, JSONRPC_NO_RESULT_STR)
        else:
            self.valid_response(res)
516560
function sendResponse(success) {
        success = success || false;
        response.status(200);
        response.contentType('application/json');
        response.send(JSON.stringify({success: success}));
      }
451094
function parse_request(){
		parent::parse_request();

		if (isset($_GET["posStart"]) && isset($_GET["count"]))
			$this->request->set_limit($_GET["posStart"],$_GET["count"]);
	}
775746
function() {
        // Send request
        var sendRequest = function() {
          debug('Calling: %s, retry: %s', entry.name, attempts - 1);
          // Make request and handle response or error
          return makeRequest(
            that,
            entry.method,
            url,
            payload,
            query
          ).then(function(res) {
            // If request was successful, accept the result
            debug('Success calling: %s, (%s retries)',
              entry.name, attempts - 1);
            if (monitor) {
              var d = process.hrtime(start);
              monitor.measure([entry.name, 'success'], d[0] * 1000 + d[1] / 1000000);
              monitor.count([entry.name, 'success']);
            }
            if (!_.includes(res.headers['content-type'], 'application/json') || !res.body) {
              debug('Empty response from server: call: %s, method: %s', entry.name, entry.method);
              return undefined;
            }
            return res.body;
          }, function(err) {
            // If we got a response we read the error code from the response
            var res = err.response;
            if (res) {
              // Decide if we should retry
              if (attempts <= that._options.retries &&
                  res.status >= 500 &&  // Check if it's a 5xx error
                  res.status < 600) {
                debug('Error calling: %s now retrying, info: %j',
                  entry.name, res.body);
                return retryRequest();
              }
              // If not retrying, construct error object and reject
              debug('Error calling: %s NOT retrying!, info: %j',
                entry.name, res.body);
              var message = 'Unknown Server Error';
              if (res.status === 401) {
                message = 'Authentication Error';
              }
              if (res.status === 500) {
                message = 'Internal Server Error';
              }
              err = new Error(res.body.message || message);
              err.body = res.body;
              err.code = res.body.code || 'UnknownError';
              err.statusCode = res.status;
              if (monitor) {
                var d = process.hrtime(start);

                var state = 'client-error';
                if (res.statusCode >= 500) {
                  state = 'server-error';
                }
                monitor.measure([entry.name, state], d[0] * 1000 + d[1] / 1000000);
                monitor.count([entry.name, state]);
              }
              throw err;
            }

            // Decide if we should retry
            if (attempts <= that._options.retries) {
              debug('Request error calling %s (retrying), err: %s, JSON: %s',
                entry.name, err, err);
              return retryRequest();
            }
            debug('Request error calling %s NOT retrying!, err: %s, JSON: %s',
              entry.name, err, err);
            if (monitor) {
              var d = process.hrtime(start);
              monitor.measure([entry.name, 'connection-error'], d[0] * 1000 + d[1] / 1000000);
              monitor.count([entry.name, 'connection-error']);
            }
            throw err;
          });
        };

        // Increment attempt count, but track how many we had before.
        attempts += 1;

        // If this is the first retry, ie we haven't retried yet, we make the
        // request immediately
        if (attempts === 1) {
          return sendRequest();
        } else {
          var delay;
          // First request is attempt = 1, so attempt = 2 is the first retry
          // we subtract one to get exponents: 1, 2, 3, 4, 5, ...
          delay = Math.pow(2, attempts - 1) * that._options.delayFactor;
          // Apply randomization factor
          var rf = that._options.randomizationFactor;
          delay *= Math.random() * 2 * rf + 1 - rf;
          // Always limit with a maximum delay
          delay = Math.min(delay, that._options.maxDelay);
          // Sleep then send the request
          return new Promise(function(accept) {
            setTimeout(accept, delay);
          }).then(function() {
            return sendRequest();
          });
        }
      }
242808
function ( params, callback, method, done ) {
			const self = this,
				// store requested action - will be used when parsing a response
				actionName = params.action,
				// "request" options
				options = {
					method: method || 'GET',
					proxy: this.proxy || false,
					jar: this.jar,
					headers: {
						'User-Agent': this.userAgent
					}
				};

			// HTTP request parameters
			params = params || {};

			// force JSON format
			params.format = 'json';

			// handle uploads
			if ( method === 'UPLOAD' ) {
				options.method = 'POST';

				const CRLF = '\r\n',
					postBody = [],
					boundary = `nodemw${Math.random().toString().substr( 2 )}`;

				// encode each field
				Object.keys( params ).forEach( function ( fieldName ) {
					const value = params[ fieldName ];

					postBody.push( `--${boundary}` );
					postBody.push( CRLF );

					if ( typeof value === 'string' ) {
					// properly encode UTF8 in binary-safe POST data
						postBody.push( `Content-Disposition: form-data; name="${fieldName}"` );
						postBody.push( CRLF );
						postBody.push( CRLF );
						postBody.push( new Buffer( value, 'utf8' ) );
					} else {
					// send attachment
						postBody.push( `Content-Disposition: form-data; name="${fieldName}"; filename="foo"` );
						postBody.push( CRLF );
						postBody.push( CRLF );
						postBody.push( value );
					}

					postBody.push( CRLF );
				} );

				postBody.push( `--${boundary}--` );

				// encode post data
				options.headers[ 'content-type' ] = `multipart/form-data; boundary=${boundary}`;
				options.body = postBody;

				params = {};
			}

			// form an URL to API
			options.url = this.formatUrl( {
				protocol: this.protocol,
				port: this.port,
				hostname: this.server,
				pathname: this.path + '/api.php',
				query: ( options.method === 'GET' ) ? params : {}
			} );

			// POST all parameters (avoid "request string too long" errors)
			if ( method === 'POST' ) {
				options.form = params;
			}

			this.logger.debug( 'API action: %s', actionName );
			this.logger.debug( '%s <%s>', options.method, options.url );
			if ( options.form ) {
				this.logger.debug( 'POST fields: %s', Object.keys( options.form ).join( ', ' ) );
			}

			request( options, function ( error, response, body ) {
				response = response || {};

				if ( error ) {
					self.logger.error( 'Request to API failed: %s', error );
					callback( new Error( `Request to API failed: ${error}` ) );
					done();
					return;
				}

				if ( response.statusCode !== 200 ) {
					self.logger.error( 'Request to API failed: HTTP status code was %d for <%s>', response.statusCode || 'unknown', options.url );
					self.logger.debug( 'Body: %s', body );

					self.logger.data( new Error().stack );

					callback( new Error( `Request to API failed: HTTP status code was ${response.statusCode}` ) );
					done();
					return;
				}

				// parse response
				let data,
					info,
					next;

				try {
					data = JSON.parse( body );
					info = data && data[ actionName ];

					// acfrom=Zeppelin Games
					next = data && data[ 'query-continue' ] && data[ 'query-continue' ][ params.list || params.prop ];

					// handle the new continuing queries introduced in MW 1.21
					// (and to be made default in MW 1.26)
					// issue #64
					// @see https://www.mediawiki.org/wiki/API:Query#Continuing_queries
					if ( !next ) {
					// cmcontinue=page|5820414e44205920424f534f4e53|12253446, continue=-||
						next = data && data.continue;
					}
				} catch ( e ) {
					self.logger.error( 'Error parsing JSON response: %s', body );
					self.logger.data( body );

					callback( new Error( 'Error parsing JSON response' ) );
					done();
					return;
				}

				// if (!callback) data.error = {info: 'foo'}; // debug

				if ( data && !data.error ) {
					if ( next ) {
						self.logger.debug( 'There\'s more data' );
						self.logger.debug( next );
					}

					callback( null, info, next, data );
				} else if ( data.error ) {
					self.logger.error( 'Error returned by API: %s', data.error.info );
					self.logger.data( data.error );

					callback( new Error( `Error returned by API: ${data.error.info}` ) );
				}
				done();
			} );
		}