Send an http request through the http client.

@param  string $method http method sent
@param  array $arguments Array containing the URI to send the request and the parameters of the request
@return \GuzzleHttp\Psr7\Response
485568
public function send($method, $arguments)
    {
        $uri = $arguments[0];
        $params = isset($arguments[1]) ? $arguments[1] : [];
        if (substr($uri, 0, 1) !== '/') {
            $uri = '/' . $uri;
        }

        $response = $this->httpClient->send(
            new Request($method, new Uri($uri)),
            $params
        );

        return $response;
    }
281541
public function apiCall($method, array $args = [])
    {
        // create the request url
        $requestUrl = self::BASE_URL . $method;

        // set the api token
        $args['token'] = $this->token;

        // send a post request with all arguments
        $promise = $this->httpClient->postAsync($requestUrl, [
            'form_params' => $args,
        ]);

        // Add requests to the event loop to be handled at a later date.
        $this->loop->futureTick(function () use ($promise) {
            $promise->wait();
        });

        // When the response has arrived, parse it and resolve. Note that our
        // promises aren't pretty; Guzzle promises are not compatible with React
        // promises, so the only Guzzle promises ever used die in here and it is
        // React from here on out.
        $deferred = new Deferred();
        $promise->then(function (ResponseInterface $response) use ($deferred) {
            // get the response as a json object
            $payload = Payload::fromJson((string) $response->getBody());

            // check if there was an error
            if (isset($payload['ok']) && $payload['ok'] === true) {
                $deferred->resolve($payload);
            } else {
                // make a nice-looking error message and throw an exception
                $niceMessage = ucfirst(str_replace('_', ' ', $payload['error']));
                $deferred->reject(new ApiException($niceMessage));
            }
        });

        return $deferred->promise();
    }
1270570
private function executeMethod($method, $args = [])
    {
        if (method_exists($this, $method)) {
            return call_user_func_array([$this, $method], $args);
        }
    }
440140
public function sendRequest($method ,$uri = null)
    {

        $this->reset();

        try {
            //log request
            $this->setLog(LogLevel::INFO, 'Try to send Request: Method: '.$method.' uri: '.$uri, $this->requestHelper->options);

            //send request
            $this->response->psr7response = $this->httpclient->request($method, $uri, $this->requestHelper->options );

            //log headers
            $this->setLog(LogLevel::INFO, 'Request send with Headers: '.$this->getHeadersString($this->response->psr7response), $this->requestHelper->options);

            // To retrive body, do not use ->getContents()
            // it turns out that this gets the “remaining contents of the body as a string”
            // and since the middleware already accessed the body (for example in order to log it),
            // there isn’t any content remaining to retrieve.
            // The correct way to access the response content is to cast the body to a string.
            // See: https://michaelstivala.com/logging-guzzle-requests/
            $this->response->body = (string) $this->response->psr7response->getBody();

            //log status code
            $this->response->status_code =  $this->response->psr7response->getStatusCode();

            //log response
            $this->setLog(LogLevel::INFO,'Response ',['status code'=>$this->response->status_code,'body'=>$this->response->body]);

        } catch (\GuzzleHttp\Exception\ClientException $e) {

            $responseStatusCode = $this->getResponseStatusCodeFromException($e);
            $this->setLog(LogLevel::ERROR,'\GuzzleHttp\Exception\ClientException',['message'=>$e->getMessage(),'path request'=>$e->getRequest()->getUri()->getPath(),'method'=>$e->getRequest()->getMethod(),'response status code'=>$responseStatusCode]);
                                            $this->setLog(LogLevel::DEBUG,'\GuzzleHttp\Exception\ClientException',['trace'=>$e->getTraceAsString()]);
            throw new \GuzzleHttp\Exception\ClientException($e->getMessage().' '.$responseStatusCode,$e->getRequest(),$e->getResponse(),$e,$e->getHandlerContext());

        } catch (\GuzzleHttp\Exception\ServerException $e) {

            $responseStatusCode = $this->getResponseStatusCodeFromException($e);
            $this->setLog(LogLevel::ERROR,'\GuzzleHttp\Exception\ServerException',['message'=>$e->getMessage(),'path request'=>$e->getRequest()->getUri()->getPath(),'method'=>$e->getRequest()->getMethod(),'response status code'=>$responseStatusCode]);
            $this->setLog(LogLevel::DEBUG,'\GuzzleHttp\Exception\ServerException',['trace'=>$e->getTraceAsString()]);
            throw new \GuzzleHttp\Exception\ServerException($e->getMessage().' '.$responseStatusCode,$e->getRequest(),$e->getResponse(),$e,$e->getHandlerContext());


        } catch (\GuzzleHttp\Exception\BadResponseException $e) {

            $responseStatusCode = $this->getResponseStatusCodeFromException($e);
            $this->setLog(LogLevel::ERROR,'\GuzzleHttp\Exception\BadResponseException',['message'=>$e->getMessage(),'path request'=>$e->getRequest()->getUri()->getPath(),'method'=>$e->getRequest()->getMethod(),'response status code'=>$responseStatusCode]);
            $this->setLog(LogLevel::DEBUG,'\GuzzleHttp\Exception\BadResponseException',['trace'=>$e->getTraceAsString()]);
            throw new \GuzzleHttp\Exception\BadResponseException($e->getMessage().' '.$responseStatusCode,$e->getRequest(),$e->getResponse(),$e,$e->getHandlerContext());

        } catch (\GuzzleHttp\Exception\ConnectException $e) {

            $responseStatusCode = $this->getResponseStatusCodeFromException($e);
            $this->setLog(LogLevel::ERROR,'\GuzzleHttp\Exception\ConnectException',['message'=>$e->getMessage(),'path request'=>$e->getRequest()->getUri()->getPath(),'method'=>$e->getRequest()->getMethod(),'response status code'=>$responseStatusCode]);
            $this->setLog(LogLevel::DEBUG,'\GuzzleHttp\Exception\ConnectException',['trace'=>$e->getTraceAsString()]);
            throw new \GuzzleHttp\Exception\ConnectException($e->getMessage().' '.$responseStatusCode,$e->getRequest(),$e,$e->getHandlerContext());

        } catch (\GuzzleHttp\Exception\TooManyRedirectsException $e) {

            $responseStatusCode = $this->getResponseStatusCodeFromException($e);
            $this->setLog(LogLevel::ERROR,'\GuzzleHttp\Exception\TooManyRedirectsException',['message'=>$e->getMessage(),'path request'=>$e->getRequest()->getUri()->getPath(),'method'=>$e->getRequest()->getMethod(),'response status code'=>$responseStatusCode]);
            $this->setLog(LogLevel::DEBUG,'\GuzzleHttp\Exception\TooManyRedirectsException',['trace'=>$e->getTraceAsString()]);
            throw new \GuzzleHttp\Exception\TooManyRedirectsException($e->getMessage().' '.$responseStatusCode,$e->getRequest(),$e->getResponse(),$e,$e->getHandlerContext());

        } catch (\GuzzleHttp\Exception\RequestException $e) {

            $responseStatusCode = $this->getResponseStatusCodeFromException($e);
            $this->setLog(LogLevel::ERROR,'\GuzzleHttp\Exception\RequestException',['message'=>$e->getMessage(),'path request'=>$e->getRequest()->getUri()->getPath(),'method'=>$e->getRequest()->getMethod(),'response status code'=>$responseStatusCode]);
            $this->setLog(LogLevel::DEBUG,'\GuzzleHttp\Exception\RequestException',['trace'=>$e->getTraceAsString()]);
            throw new \GuzzleHttp\Exception\RequestException($e->getMessage().' '.$responseStatusCode,$e->getRequest(),$e->getResponse(),$e,$e->getHandlerContext());

        } catch (\GuzzleHttp\Exception\TransferException $e) {

            $this->setLog(LogLevel::ERROR,'\GuzzleHttp\Exception\TransferException',['message'=>$e->getMessage(),'code'=>$e->getCode()]);
            $this->setLog(LogLevel::DEBUG,'\GuzzleHttp\Exception\TransferException',['trace'=>$e->getTraceAsString()]);
            throw new \GuzzleHttp\Exception\TransferException($e->getMessage(),$e->getCode(),$e);

        } catch (\RuntimeException $e) {

            $this->setLog(LogLevel::ERROR,'\RuntimeException',['message'=>$e->getMessage(),'code'=>$e->getCode()]);
            $this->setLog(LogLevel::DEBUG,'\RuntimeException',['trace'=>$e->getTraceAsString()]);
            throw new \RuntimeException($e->getMessage(),$e->getCode(),$e);

        }

        return $this->response;
    }
1215313
public function notify($method, array $arguments)
    {
        $message = array(
            'jsonrpc' => self::VERSION,
            'method' => $method
        );

        if ($arguments !== null) {
            $message['params'] = $arguments;
        }

        $this->messages[] = $message;
        return $this;
    }
1367621
private function call($method, array $args)
    {
        $request = $this->rpcProtocol->encodeRequest($method, $args);

        $response = $this->transport->request($request);

        $response = $this->rpcProtocol->decodeValue($response);

        if ($response instanceof \Exception) {
            throw $response;
        }

        return $response;
    }
945325
public function request(string $method, string $path, array $parameters = [])
    {
        $options = [
            'headers' => [
                'Authorization' => sprintf('Key %s', $this->apiKey),
                'User-Agent' => sprintf(
                  'Clarifai PHP (https://github.com/darrynten/clarifai-php);v%s;%s',
                  \DarrynTen\Clarifai\Clarifai::VERSION,
                  phpversion()
                ),
            ],
        ];

        // TODO check for batch operation
        return $this->handleRequest(
            $method,
            sprintf('%s/%s/%s', $this->url, $this->version, $path),
            $options,
            $parameters
        );
    }
1363640
private function send (string $method, array $params)
		{

			$request = xmlrpc_encode_request($method, $params);

			$context = stream_context_create([ 'http' => [
				'method'  => "GET",
				'header'  => "Content-Type: text/xml",
				'content' => $request
			] ]);

			$file = file_get_contents($this->_url, false, $context);

			return xmlrpc_decode($file);
		}
374614
protected static function _httpRequest( $method = self::GET, $url, $payload = array(), $curlOptions = array() )
    {
        if ( !static::contains( $method ) )
        {
            throw new \InvalidArgumentException( 'Invalid method "' . $method . '" specified.' );
        }

        //	Reset!
        static::$_lastResponseHeaders = static::$_lastHttpCode = static::$_error = static::$_info = $_tmpFile = null;

        //	Build a curl request...
        $_curl = curl_init( $url );

        //	Default CURL options for this method
        $_curlOptions = array(
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => true,
            CURLINFO_HEADER_OUT    => true,
            CURLOPT_SSL_VERIFYPEER => false,
        );

        //	Merge in the global options if any
        if ( !empty( static::$_curlOptions ) )
        {
            $curlOptions = array_merge(
                $curlOptions,
                static::$_curlOptions
            );
        }

        //	Add/override user options
        if ( !empty( $curlOptions ) )
        {
            foreach ( $curlOptions as $_key => $_value )
            {
                $_curlOptions[$_key] = $_value;
            }
        }

        if ( null !== static::$_userName || null !== static::$_password )
        {
            $_curlOptions[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
            $_curlOptions[CURLOPT_USERPWD] = static::$_userName . ':' . static::$_password;
        }

        switch ( $method )
        {
            case static::GET:
                //	Do nothing, like the goggles...
                break;

            case static::PUT:
                if (static::$putAsFile)
                {
                    $_payload = json_encode(!empty($payload) ? $payload : []);

                    $_tmpFile = tmpfile();
                    fwrite($_tmpFile, $_payload);
                    rewind($_tmpFile);

                    $_curlOptions[CURLOPT_PUT] = true;
                    $_curlOptions[CURLOPT_INFILE] = $_tmpFile;
                    $_curlOptions[CURLOPT_INFILESIZE] = mb_strlen($_payload);
                }
                else
                {
                    $_curlOptions[CURLOPT_CUSTOMREQUEST] = static::PUT;
                    $_curlOptions[CURLOPT_POSTFIELDS] = $payload;
                }
                break;

            case static::POST:
                $_curlOptions[CURLOPT_POST] = true;
                $_curlOptions[CURLOPT_POSTFIELDS] = $payload;
                break;

            case static::HEAD:
                $_curlOptions[CURLOPT_NOBODY] = true;
                break;

            case static::PATCH:
                $_curlOptions[CURLOPT_CUSTOMREQUEST] = static::PATCH;
                $_curlOptions[CURLOPT_POSTFIELDS] = $payload;
                break;

            case static::MERGE:
            case static::DELETE:
                /** Merge && Delete have payloads, but they and Options/Copy need CURLOPT_CUSTOMREQUEST set so just fall through... */
                $_curlOptions[CURLOPT_POSTFIELDS] = $payload;
            //  intentional drop through...
            case static::OPTIONS:
            case static::COPY:
                $_curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
                break;
        }

        if ( null !== static::$_hostPort && !isset( $_curlOptions[CURLOPT_PORT] ) )
        {
            $_curlOptions[CURLOPT_PORT] = static::$_hostPort;
        }

        //	Set our collected options
        curl_setopt_array( $_curl, $_curlOptions );

        //	Make the call!
        $_result = curl_exec( $_curl );

        static::$_info = curl_getinfo( $_curl );
        static::$_lastHttpCode = Option::get( static::$_info, 'http_code' );
        static::$_responseHeaders = curl_getinfo( $_curl, CURLINFO_HEADER_OUT );
        static::$_responseHeadersSize = curl_getinfo( $_curl, CURLINFO_HEADER_SIZE );

        if ( static::$_debug )
        {
            //	@todo Add debug output
        }

        if ( false === $_result )
        {
            static::$_error = array(
                'code'    => curl_errno( $_curl ),
                'message' => curl_error( $_curl ),
            );
        }
        elseif ( true === $_result )
        {
            //	Worked, but no data...
            $_result = null;
        }
        else
        {
            //      Split up the body and headers if requested
            if ( $_curlOptions[CURLOPT_HEADER] )
            {
                if ( false === strpos( $_result, "\r\n\r\n" ) || empty( static::$_responseHeadersSize ) )
                {
                    $_headers = $_result;
                    $_body = null;
                }
                else
                {
                    $_headers = substr( $_result, 0, static::$_responseHeadersSize );
                    $_body = substr( $_result, static::$_responseHeadersSize );
                }

                if ( $_headers )
                {
                    static::$_lastResponseHeaders = array();
                    $_raw = explode( "\r\n", $_headers );

                    if ( !empty( $_raw ) )
                    {
                        $_first = true;

                        foreach ( $_raw as $_line )
                        {
                            //	Skip the first line (HTTP/1.x response)
                            if ( $_first || preg_match( '/^HTTP\/[0-9\.]+ [0-9]+/', $_line ) )
                            {
                                $_first = false;
                                continue;
                            }

                            $_parts = explode( ':', $_line, 2 );

                            if ( !empty( $_parts ) )
                            {
                                static::$_lastResponseHeaders[trim( $_parts[0] )] = count( $_parts ) > 1 ? trim( $_parts[1] ) : null;
                            }
                        }
                    }
                }

                $_result = $_body;
            }

            //	Attempt to auto-decode inbound JSON
            if ( !empty( $_result ) && false !== stripos( Option::get( static::$_info, 'content_type' ), 'application/json', 0 ) )
            {
                try
                {
                    if ( false !== ( $_json = @json_decode( $_result, static::$_decodeToArray ) ) )
                    {
                        $_result = $_json;
                    }
                }
                catch ( \Exception $_ex )
                {
                    //	Ignored
                    Log::debug( 'Exception decoding result: ' . $_ex->getMessage() );
                }
            }

            //	Don't confuse error with empty data...
            if ( false === $_result )
            {
                $_result = null;
            }
        }

        @curl_close( $_curl );

        //	Close temp file if any
        if ( null !== $_tmpFile )
        {
            @fclose( $_tmpFile );
        }

        return $_result;
    }
1213052
public function remoteHttpCall($method, array $args)
    {
        $reqParams = [
            'version'   => static::$version,
            'args'      => array_values($args),
            'time'      => microtime(true),
            'handler'   => $this->handler,
            'construct' => $this->construct,
            'method'    => $method
        ];
        $sendData = [
            'data' => getInstance()->pack->pack($reqParams),
        ];
        $headers = [
            'X-RPC' => 1,
        ];

        /**
         * @var Client $client
         */
        $client = yield $this->getObject(Client::class)->goDnsLookup($this->host, $this->timeout, $headers);
        if (!$client) {
            throw new Exception($this->host . ' dns query failed');
        }

        $urlPath = '/' .$this->urlPath . '/' . $this->service . '/' . $this->handler . '/' . $this->method;
        if ($this->verb == 'POST') {
            $response = yield $client->goPost($urlPath, $sendData, $this->timeout);
        } else {
            $response = yield $client->goGet($urlPath, $sendData, $this->timeout);
        }

        if ($response && !empty($response['body']) && ($jsonRes = json_decode($response['body'], true))) {
            if ($response['statusCode'] !== 200) {
                $this->getContext()->getLog()->warning(dump($response, false, true));
                return false;
            } else {
                return $jsonRes;
            }
        } else {
            $this->getContext()->getLog()->warning(dump($response, false, true));
            return false;
        }
    }
410522
private function requestAPI($method, $url, array $options = [])
    {
        try {
            return $this->sendRequest((string)$method, (string)$url, $options);
        } catch (SessionWasExpiredException $e) {
            return $this->sendRequest((string)$method, (string)$url, $options);
        } catch (ClientException $e) {
            throw new BunqException($e);
        }
    }
881260
public function invoke($object, $method, array $arguments = [])
    {
        $reflection = new \ReflectionClass($object);
        $method = $reflection->getMethod($method);
        $args = $this->resolveArguments($method, $arguments);

        return $method->invokeArgs($object, $args);
    }
902057
public function send($method,$arg1="",$arg2="") {

        // if we have a string, send it as well
        if($arg1 != "" && $arg2 != "")
        {
            $command = "$method \"$arg1\" \"$arg2\"";
        }
        elseif($arg1 != "") {
            $command = "$method \"$arg1\"";
        }
        else {
            $command = $method;
        }


        fputs($this->fp,"$command\n"); //Do desired action!
        $c = 0;
        while(!feof($this->fp)) {
            $got =  fgets($this->fp,1024);
            if(strncmp("OK",$got,strlen("OK"))==0)
                break;
            if(strncmp("ACK",$got,strlen("ACK"))==0)
                break;

            $ret[$c]=$got;
            $c++;
        }

        $sentResponse = array(
            "response" => $this->response,
            "got" => $got,
            "ret" => $ret
        );
        return $sentResponse;

    }
717272
protected function request($method, $url, $parameters = array())
    {
        Logger::get()->debug('HTTP: starting request...');
        $headers = $this->headers;

        // Add accepted content type header.
        $headers[] = 'Content-Type: ' . $this->contentType;
        $headers[] = 'Accept: ' . $this->acceptedContentType;

        $handler = curl_init();

        if (!is_null($this->user)) {
            curl_setopt($handler, CURLOPT_USERPWD, $this->user . ':' . $this->password);
        }

        Logger::get()->debug('HTTP: method is ' . $method);
        switch ($method) {
            case self::METHOD_DELETE:
                curl_setopt($handler, CURLOPT_URL, $url . '?' . http_build_query($parameters));
                curl_setopt($handler, CURLOPT_CUSTOMREQUEST, self::DELETE);
                break;
            case self::METHOD_POST:
                curl_setopt($handler, CURLOPT_URL, $url);
                curl_setopt($handler, CURLOPT_POST, true);
                curl_setopt($handler, CURLOPT_POSTFIELDS, $parameters);
                break;
            case self::METHOD_GET:
                curl_setopt($handler, CURLOPT_URL, $url . '?' . http_build_query($parameters));
                break;
        }

        curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handler, CURLOPT_HTTPHEADER, $headers);
        Logger::get()->debug('HTTP: headers set.');

        // Send the request to the server.
        Logger::get()->debug("HTTP: requesting $url...");
        $output = curl_exec($handler);
        $errNo = curl_errno($handler);
        $error = curl_error($handler);
        // Obtain the status.
        Logger::get()->debug('HTTP: Done. Getting status...');
        $status = curl_getinfo($handler, CURLINFO_HTTP_CODE);
        // The handler is no longer needed.
        curl_close($handler);
        Logger::get()->debug('HTTP: request finished.');

        if ($errNo) {
            throw new Exception('HTTP: cURL failed: ' . $error, $errNo);
        }

        // If cURL had no errors itself, then there is an HTTP response.
        switch ($status) {
            case self::STATUS_OK:
            case self::STATUS_CREATED:
            case self::STATUS_ACCEPTED:
            case self::STATUS_NO_CONTENT:
                return $output;
            default:
                throw new Http\Exception("HTTP {$status}", $status);
        }
    }
469965
protected function writeRequest($method, $arguments, callable $callback = null)
    {
        $arguments = Command::normalizeArguments($arguments ?: []);
        $command = $this->client->createCommand($method, $arguments);

        $this->client->executeCommand($command, $callback);
    }
360934
private function sendRequest($method, $url, array $options = [])
    {
        $response = $this->httpClient->request((string)$method, $url, $options);

        return json_decode($response->getBody(), true);
    }
333756
public static function __callstatic($method, $arguments)
	{
		$content = count($arguments) ? $arguments[0] : null;
		return self::createSub($method, $content);
	}