Dispatches a request via CURL
431233
private function dispatchRequest($request)
    {
        // track the number of requests across instances
        self::$requestCount++;
        $timestart = microtime(true);

        $response = self::transport()->send($request);

        // pass the response through the filter chain
        foreach ($this->filters as $filter) {
            $response = $filter->response($response);
        }

        $httpCode = $response->getStatus()->getCode();
        $location = $response->getHeaders()->value('Location');
        $body = $response->getBody();

        // track the time taken across instances
        self::$requestTime += microtime(true) - $timestart;

        // process a redirect if needed
        if ($httpCode < 400 && $location) {
            return $this->redirect($location);
        } else {
            $this->redirects = 0;
        }

        // translate error code to a typed exception
        if ($httpCode == 500) {
            throw new Error\InternalServerError($body);
        } elseif ($httpCode == 400) {
            throw new Error\BadRequest($body);
        } elseif ($httpCode == 401) {
            throw new Error\Unauthorized($body);
        } elseif ($httpCode == 404) {
            throw new Error\NotFound($body);
        } elseif ($httpCode >= 300) {
            throw new Error($body, $httpCode);
        }

        return $response;
    }
921422
def dispatch(self, request, **kwargs):
        '''
        
        '''

        # Delete method must happen with POST not with GET
        if request.method == 'POST':
            # Check if this is a webservice request
            self.__authtoken = (bool(getattr(self.request, "authtoken", False)))
            self.json_worker = self.__authtoken or (self.json is True)
            # Call the base implementation
            return super(GenDelete, self).dispatch(request, **kwargs)
        else:
            json_answer = json.dumps({
                'error': True,
                'errortxt': _('Method not allowed, use POST to delete or DELETE on the detail url'),
                })
            return HttpResponse(json_answer, content_type='application/json')
695850
def dispatch_request(self, *args, **kwargs):
        """"""
        method = getattr(self, request.method.lower(), None)
        if method is None and request.method == 'HEAD':
            method = getattr(self, 'get', None)
        assert method is not None, 'Unimplemented method {}'.format(request.method)

        headers = {'Content-Type': 'application/vnd.api+json'}

        response = method(*args, **kwargs)

        if isinstance(response, Response):
            response.headers.add('Content-Type', 'application/vnd.api+json')
            return response

        if not isinstance(response, tuple):
            if isinstance(response, dict):
                response.update({'jsonapi': {'version': '1.0'}})
            return make_response(json.dumps(response, cls=JSONEncoder), 200, headers)

        try:
            data, status_code, headers = response
            headers.update({'Content-Type': 'application/vnd.api+json'})
        except ValueError:
            pass

        try:
            data, status_code = response
        except ValueError:
            pass

        if isinstance(data, dict):
            data.update({'jsonapi': {'version': '1.0'}})

        return make_response(json.dumps(data, cls=JSONEncoder), status_code, headers)
4488
def dispatch(self, request, **resources):
        

        # Fix PUT and PATH methods in Django request
        request = fix_request(request)

        # Set self identifier
        self.identifier = request.META.get('REMOTE_ADDR', 'anonymous')

        # Send ADREST started signal
        api_request_started.send(self, request=request)

        # Send current api started signal
        if self.api:
            self.api.request_started.send(self, request=request)

        try:

            # Check request method
            self.check_method_allowed(request)

            # Authentificate
            self.authenticate(request)

            # Throttle check
            self.throttle_check()

            if request.method != 'OPTIONS' or not ADREST_ALLOW_OPTIONS:

                # Parse content
                request.data = self.parse(request)

                # Get required resources
                resources = self.get_resources(
                    request, **resources)

                # Check owners
                self.check_owners(request, **resources)

                # Check rights for resources with this method
                self.check_rights(resources, request=request)

            response = self.handle_request(request, **resources)

            # Serialize response
            response = self.emit(response, request=request)

        except Exception as e:
            response = self.handle_exception(e, request=request)

        response["Allow"] = ', '.join(self._meta.allowed_methods)
        response["Vary"] = 'Authenticate, Accept'

        # Send errors on mail
        adrest_errors_mail(response, request)

        # Send finished signal
        api_request_finished.send(
            self, request=request, response=response, **resources)

        # Send finished signal in API context
        if self.api:
            self.api.request_finished.send(
                self, request=request, response=response, **resources)

        return response
1012044
public function dispatch()
    {
        if (php_sapi_name() === 'cli' || defined('STDIN')) {

            global $argv;

            App::resolve('Cli', [array_slice($argv, 1), $this]);

            exit();
        }

        $this->execute()->respond()->terminate();
    }
144828
private function curl_request($url = '')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
426997
async def dispatch(self, request, **kwargs):
        """"""
        # Authorize request
        self.auth = await self.authorize(request)

        # Load collection
        self.collection = await self.load_many(request)

        # Load resource
        self.resource = await self.load_one(request)

        if request.method == 'GET' and self.resource is None:

            # Filter collection
            self.collection = await self.filter(request)

            # Sort collection
            self.columns_sort = request.query.get('ap-sort', self.columns_sort)
            if self.columns_sort:
                reverse = self.columns_sort.startswith('-')
                self.columns_sort = self.columns_sort.lstrip('+-')
                self.collection = await self.sort(request, reverse=reverse)

            # Paginate collection
            try:
                self.offset = int(request.query.get('ap-offset', 0))
                if self.limit:
                    self.count = await self.count(request)
                    self.collection = await self.paginate(request)
            except ValueError:
                pass

        return await super(AdminHandler, self).dispatch(request, **kwargs)
487866
def dispatch_request(self, environ, start_response):
        """"""
        # set up all the stuff we want to have for this request.  That is
        # creating a request object, propagating the application to the
        # current context and instanciating the database session.
        self.bind_to_context()
        request = Request(environ)
        request.bind_to_context()

        # get the current action from the url and normalize the page name
        # which is just the request path
        action_name = request.args.get("action") or "show"
        page_name = u"_".join([x for x in request.path.strip("/").split() if x])

        # redirect to the Main_Page if the user requested the index
        if not page_name:
            response = redirect(href("Main_Page"))

        # check special pages
        elif page_name.startswith("Special:"):
            if page_name[8:] not in pages:
                response = page_not_found(request, page_name)
            else:
                response = pages[page_name[8:]](request)

        # get the callback function for the requested action from the
        # action module.  It's "on_" + the action name.  If it doesn't
        # exists call the missing_action method from the same module.
        else:
            action = getattr(actions, "on_" + action_name, None)
            if action is None:
                response = actions.missing_action(request, action_name)
            else:
                response = action(request, page_name)

        # make sure the session is removed properly
        return ClosingIterator(response(environ, start_response), session.remove)
339969
def request(self, msgtype, msgid, method, params=[]):
        """"""
        result = None
        error = None
        exception = None

        try:
            result = self.dispatch.call(method, params)
        except Exception as e:
            error = (e.__class__.__name__, str(e))
            exception = e

        if isinstance(result, Deferred):
            result.add_callback(self._result, msgid)
            result.add_errback(self._error, msgid)
        else:
            self.send_response(msgid, error, result)
389641
public static function dispatch()
    {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $method = $_SERVER['REQUEST_METHOD'];

        $searches = array_keys(static::$patterns);
        $replaces = array_values(static::$patterns);

        $found_route = false;

        self::$routes = preg_replace('/\/+/', '/', self::$routes);

        // Check if route is defined without regex
        if (in_array($uri, self::$routes)) {
            $route_pos = array_keys(self::$routes, $uri);
            foreach ($route_pos as $route) {

                // Using an ANY option to match both GET and POST requests
                if (self::$methods[$route] == $method || self::$methods[$route] == 'ANY' || in_array($method, self::$maps[$route])) {
                    $found_route = true;

                    // If route is not an object
                    if (!is_object(self::$callbacks[$route])) {

                        // Grab all parts based on a / separator
                        $parts = explode('/', self::$callbacks[$route]);

                        // Collect the last index of the array
                        $last = end($parts);

                        // Grab the controller name and method call
                        $segments = explode('@', $last);

                        // Instanitate controller
                        $controller = new $segments[0]();

                        // Call method
                        $controller->{$segments[1]}();

                        if (self::$halts) return;
                    } else {
                        // Call closure
                        call_user_func(self::$callbacks[$route]);

                        if (self::$halts) return;
                    }
                }
            }
        } else {
            // Check if defined with regex
            $pos = 0;
            foreach (self::$routes as $route) {
                if (strpos($route, ':') !== false) {
                    $route = str_replace($searches, $replaces, $route);
                }

                if (preg_match('#^' . $route . '$#', $uri, $matched)) {
                    if (self::$methods[$pos] == $method || self::$methods[$pos] == 'ANY' || in_array($method, self::$maps[$pos])) {
                        $found_route = true;

                        // Remove $matched[0] as [1] is the first parameter.
                        array_shift($matched);

                        if (!is_object(self::$callbacks[$pos])) {

                            // Grab all parts based on a / separator
                            $parts = explode('/', self::$callbacks[$pos]);

                            // Collect the last index of the array
                            $last = end($parts);

                            // Grab the controller name and method call
                            $segments = explode('@', $last);

                            // Instanitate controller
                            $controller = new $segments[0]();

                            // Fix multi parameters
                            if (!method_exists($controller, $segments[1])) {
                                echo "controller and action not found";
                            } else {
                                call_user_func_array(array($controller, $segments[1]), $matched);
                            }

                            if (self::$halts) return;
                        } else {
                            call_user_func_array(self::$callbacks[$pos], $matched);

                            if (self::$halts) return;
                        }
                    }
                }
                $pos++;
            }
        }

        // Run the error callback if the route was not found
        if ($found_route == false) {
            if (!self::$error_callback) {
                self::$error_callback = function () {
                    header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
                    throw new \Exception(Config::get('error_message'));
                };
            } else {
                if (is_string(self::$error_callback)) {
                    self::get($_SERVER['REQUEST_URI'], self::$error_callback);
                    self::$error_callback = null;
                    self::dispatch();
                    return;
                }
            }
            call_user_func(self::$error_callback);
        }
    }
415051
function handleRequest(url, options, callback) {
  let req = {
    url: url,
    headers: {},
    qs: {},
    json: {},
  }

  req = parseOptions(req, options)
  callback(req)
}
1373461
public function sendRequest()
    {
        if ($this->error->hasError() || !$this->http) {
            return;
        }

        if (class_exists($this->dispatcher)) {
            $dispatcherClass = $this->dispatcher;
            $dispatcher = new $dispatcherClass($this->instance->getQuery());
            if ($dispatcher instanceof AbstractDispatcher) {
                $payload = array(
                    'data' => json_encode(array(
                        'config' => $this->config->getRawConfig(),
                        'sql' => $this->instance->getQuery()->toString(),
                        'limit' => $this->instance->getQuery()->getLimit(),
                        'offset' => $this->instance->getQuery()->getOffset(),
                        'single' => $this->instance->getQuery()->isSingle(),
                    )),
                    'key' => $this->key,
                    'method' => $this->method,
                );
                $jsonResult = '[]';

                try {
                    // Guzzle Old
                    if (get_class($this->http) == 'Guzzle\Http\Client') {
                        $request = $this->http->post($this->url, array(), $payload);
                        $response = $request->send();
                        $jsonResult = $response->getBody(true);
                    }
                    // Guzzle 5+
                    elseif (get_class($this->http) == 'GuzzleHttp\Client') {
                        $response = $this->http->request('POST', $this->url, array('form_params' => $payload));
                        $jsonResult = $response->getBody();
                    }
                    // Builtin http client request
                    elseif ($this->http instanceof BuiltinRestClient) {
                        $jsonResult = self::post($this->url, $payload);
                    }

                    if ($this->method == 'getAvailableDrivers') {
                        $this->availableDrivers = json_decode((string) $jsonResult, true);
                    } elseif ($this->method == 'getServerVersion') {
                        $res = json_decode((string) $jsonResult, true);
                        $this->serverVersion = isset($res['version']) ? $res['version'] : null;
                    } else {
                        $dispatcher->dispatch((string) $jsonResult);
                    }
                } catch (\Exception $e) {
                    $this->error->setMessage(strip_tags($e->getMessage()));
                }
            } else {
                $this->error->setMessage(sprintf(
                    'Dispatcher class must be instance of %s, %s given',
                    AbstractDispatcher::class,
                    (string) $this->dispatcher
                ));
            }
        } else {
            $this->error->setMessage(sprintf('Class %s not found', (string) $this->dispatcher));
        }
    }
840987
protected function call()
    {
        // Check if the curl object is set
        if (!$this->isInit()) {
            // If it isn't, we do it right now
            $this->init();
        }

        $options = array();
        // Set basic authentication if enabled
        if ($this->authentication instanceof BasicAuthentication) {
            $options['auth'] = array(
                $this->authentication->getUsername(),
                $this->authentication->getPassword()
            );
        }

        // Set json
        if (($json = $this->getJson()) != null) {
            $options['json'] = $json;
            $this->setAccept('application/json');
        }

        if (($formParams = $this->getFormParams()) != null) {
            $options['body'] = $formParams;
            $this->setContentType('application/x-www-form-urlencoded');
        }

        $request = $this->getHttpClient()->createRequest(
            $this->getHttpMethod(),
            $this->getEndpoint(),
            array_merge(
                array('headers' => $this->getHeaders()),
                $options
            )
        );

        foreach ($this->getEndpointParameters() as $key => $value) {
            $request->getQuery()->set($key, $value);
        }

        if (($body = $this->getBody()) != null && (is_null($body))) {
            $request->setBody(Stream::factory($body));
        }

        $response = $this->getHttpClient()->send($request);

        $this->setHttpStatusCode($response->getStatusCode());

        $this->setData($response->json());
    }
146499
static function CurlRequest($method, $url, $data, $verify_cert = false, $timeout = 30)
	{
		// if the data provided is in array format, convert it to a querystring
		$qs = HttpRequest::ArrayToQueryString($data);

		$agent = "verysimple::HttpRequest";

		// $header[] = "Accept: text/vnd.wap.wml,*.*";

		$fp = null;

		if ($method == "POST")
		{
			$ch = curl_init($url);
			curl_setopt($ch,		CURLOPT_POST, 1);
			curl_setopt($ch,		CURLOPT_POSTFIELDS, $qs);
		}
		elseif ($method == 'PUT')
		{
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_PUT, true);

			if ($data)
			{
				// with a PUT request the body must be written to a file stream
				$fp = fopen('php://temp/maxmemory:256000', 'w');
				if (!$fp) {
					throw new Exception('Unable to write to php://temp for PUT request');
				}
				fwrite($fp, $data);
				fseek($fp, 0);

				// if the PUT request contains JSON data then add the content type header
				if (json_encode($data)) curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json") );

				curl_setopt($ch, CURLOPT_INFILE, $fp);
				curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
				curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
			}

		}
		else
		{
			$full_url = $url . ($qs ? "?" . $qs : "");
			$ch = curl_init($full_url);
		}

		curl_setopt($ch,		CURLOPT_HTTPHEADER, array("Expect:  ") );  //Fixes the HTTP/1.1 417 Expectation Failed Bug
		
		curl_setopt($ch,		CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch,		CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch,		CURLOPT_VERBOSE, 0); ########### debug
		curl_setopt($ch,	    CURLOPT_USERAGENT, $agent);
		curl_setopt($ch,		CURLOPT_SSL_VERIFYPEER, $verify_cert);
		curl_setopt($ch,		CURLOPT_NOPROGRESS, 1);
		// curl_setopt($ch,	    CURLOPT_HTTPHEADER, $header);
		// curl_setopt($ch,		CURLOPT_COOKIEJAR, "curl_cookie");
		// curl_setopt($ch,		CURLOPT_COOKIEFILE, "curl_cookie");
		curl_setopt($ch,		CURLOPT_TIMEOUT,$timeout);

		$tmp = curl_exec ($ch);
		$error = curl_error($ch);

		if ($fp) @fclose($fp); // if a PUT request had body data, close the file stream

		if ($error != "") {$tmp .= $error;}
		curl_close ($ch);

		return $tmp;
	}
823244
protected function _makeRequest()
    {
        # Check for cURL. If it isn't loaded, fall back to fopen()
        if(function_exists('curl_init'))
            $this->_rawResponse = $this->_makeCurlRequest($this->_url);
        else
            $this->_rawResponse = $this->_makeFOpenRequest($this->_url);
    }
613799
def dispatch(environ):
    '''
    
    '''
    method = environ['REQUEST_METHOD'].upper()

    if method == 'GET':
        return ("They found me. I don't know how, but they found me. "
                "Run for it, Marty!")
    elif method == 'POST':
        data = get_json(environ)
        return run_chunk(environ, data)
    else:
        raise HTTPError(405, 'Method Not Allowed')
1311948
def dispatch_cgi(request, cgi)
			result = @target.run( request, cgi )
			result.headers.reject!{|k,v| k.to_s.downcase == "status" }
			result.to_a
		end