Process HTTP request.
@param  string  URL or twitter command
@param  string  HTTP method GET or POST
@param  array   data
@param  array   uploaded files
@return stdClass|stdClass[]
@throws TwitterException
487891
public static function request($resource, $method, array $data = null, array $files = null)
    {
        if (!strpos($resource, '://')) {
            if (!strpos($resource, '.')) {
                $resource .= '.json';
            }
            $resource = self::API_URL . $resource;
        }

        $hasCURLFile = class_exists('CURLFile', false) && defined('CURLOPT_SAFE_UPLOAD');

        foreach ((array) $data as $key => $val) {
            if ($val === null) {
                unset($data[$key]);
            } elseif ($files && !$hasCURLFile && substr($val, 0, 1) === '@') {
                throw new TwitterException('Due to limitation of cURL it is not possible to send message starting with @ and upload file at the same time in PHP < 5.5');
            }
        }

        foreach ((array) $files as $key => $file) {
            if (!is_file($file)) {
                throw new TwitterException("Cannot read the file $file. Check if file exists on disk and check its permissions.");
            }
            $data[$key] = $hasCURLFile ? new \CURLFile($file) : '@' . $file;
        }

        $request = Twitter_OAuthRequest::from_consumer_and_token(self::$consumer, self::$token, $method, $resource, $files ? [] : $data);
        $request->sign_request(new Twitter_OAuthSignatureMethod_HMAC_SHA1, self::$consumer, self::$token);

        $options = [
                CURLOPT_HEADER => false,
                CURLOPT_RETURNTRANSFER => true,
            ] + ($method === 'POST' ? [
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $files ? $data : $request->to_postdata(),
                CURLOPT_URL => $files ? $request->to_url() : $request->get_normalized_http_url(),
            ] : [
                CURLOPT_URL => $request->to_url(),
            ]) + self::$httpOptions;

        if ($method === 'POST' && $hasCURLFile) {
            $options[CURLOPT_SAFE_UPLOAD] = true;
        }

        $curl = curl_init();
        curl_setopt_array($curl, $options);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            throw new TwitterException('Server error: ' . curl_error($curl));
        }

        $payload = defined('JSON_BIGINT_AS_STRING')
            ? @json_decode($result, false, 128, JSON_BIGINT_AS_STRING)
            : @json_decode($result); // intentionally @

        if ($payload === false) {
            throw new TwitterException('Invalid server response');
        }

        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($code >= 400) {
            throw new TwitterException(isset($payload->errors[0]->message)
                ? $payload->errors[0]->message
                : "Server error #$code with answer $result",
                $code
            );
        }

        return $payload;
    }
8699
public function upload($url, array $queries = [], array $files = [], array $form = [])
    {
        $multipart = [];

        foreach ($files as $name => $path) {
            if (is_array($path)){
                foreach ($path as $item) {
                    $multipart[] = [
                            'name' => $name . '[]',
                        ] + $item;
                }
            }else{
                $multipart[] = [
                        'name' => $name,
                    ] + $path;
            }
        }

        foreach ($form as $name => $contents) {
            $multipart[] = compact('name', 'contents');
        }

        return $this->request('POST', $url, ['query' => $queries, 'multipart' => $multipart]);
    }
1369465
def _request(self, url, method='GET', params=None, api_call=None, json_encoded=False):
        """"""
        method = method.lower()
        params = params or {}

        func = getattr(self.client, method)
        if isinstance(params, dict) and json_encoded is False:
            params, files = _transparent_params(params)
        else:
            params = params
            files = list()

        requests_args = {}
        for k, v in self.client_args.items():
            # Maybe this should be set as a class variable and only done once?
            if k in ('timeout', 'allow_redirects', 'stream', 'verify'):
                requests_args[k] = v

        if method == 'get' or method == 'delete':
            requests_args['params'] = params
        else:
            # Check for json_encoded so we will sent params as "data" or "json"
            if json_encoded:
                data_key = 'json'
            else:
                data_key = 'data'
            requests_args.update({
                data_key: params,
                'files': files,
            })
        try:
            response = func(url, **requests_args)
        except requests.RequestException as e:
            raise TwythonError(str(e))

        # create stash for last function intel
        self._last_call = {
            'api_call': api_call,
            'api_error': None,
            'cookies': response.cookies,
            'headers': response.headers,
            'status_code': response.status_code,
            'url': response.url,
            'content': response.text,
        }

        # greater than 304 (not modified) is an error
        if response.status_code > 304:
            error_message = self._get_error_message(response)
            self._last_call['api_error'] = error_message

            ExceptionType = TwythonError
            if response.status_code == 429:
                # Twitter API 1.1, always return 429 when
                # rate limit is exceeded
                ExceptionType = TwythonRateLimitError
            elif response.status_code == 401 or 'Bad Authentication data' \
                    in error_message:
                # Twitter API 1.1, returns a 401 Unauthorized or
                # a 400 "Bad Authentication data" for invalid/expired
                # app keys/user tokens
                ExceptionType = TwythonAuthError

            raise ExceptionType(
                error_message,
                error_code=response.status_code,
                retry_after=response.headers.get('X-Rate-Limit-Reset'))
        content = ''
        try:
            if response.status_code == 204:
                content = response.content
            else:
                content = response.json()
        except ValueError:
            if response.content != '':
                raise TwythonError('Response was not valid JSON. \
                                   Unable to decode.')

        return content
640823
private function processResults($results)
        {
            if (!empty($results->errors))
            {
                throw new ErrorFetchingTwitter();
            }

            $response = [];

            foreach ($results->statuses as $tweet)
            {
                $response[] = $tweet->text;
            }

            return $response;
        }
1045867
public function Request($url, $method = 'GET', $data = array(), $forceReq = false) {

    $start = microtime(true);
    $this->LoopCount++;
    $postStr    = '';
    $cookieFile = '';
    $method     = strtoupper($method);

    if (!$this->ValidUrl($url)) {
      throw new Exception('Illegal value argument url');
    }

    if (!$this->ValidMethod($method)) {
      throw new Exception('Illegal value argument method');
    }

    if ($method == 'POST' && !is_array($data)) {
      throw new Exception('Method POST requires argument data to be array');
    }

    if (!is_integer($this->maxRedirects) || $this->maxRedirects < 0) {
      throw new Exception('Property maxRedirects must be integer >= 0');
    }

    if (empty($this->useragent)) {
      $this->useragent = 'Mozilla/5.0 (curlMaster/'. self::VERSION .'; +https://github.com/peterkahl/curlMaster)';
    }

    if (empty($this->CipherString)) {
      $this->CipherString = '';
    }

    $filenameHash = sha1($method . $url . serialize($this->headers) . serialize($data) . $this->useragent) . $this->CipherString;

    if (!$forceReq && $this->ForcedCacheMaxAge >= 0) {
      if ($this->PurgeEnableOnEachRequest) {
        $this->PurgeCache();
      }
      foreach (glob($this->CacheDir .'/CURL_RESPON-*') as $cfile) {
        $temp = str_replace($this->CacheDir, '', $cfile);
        $temp = substr($temp, 13, 40);
        if ($filenameHash == $temp && file_exists($cfile)) {
          $str = $this->FileGetContents($cfile);
          $arr = unserialize($str);
          $arr['origin']   = 'cache';
          $arr['exectime'] = $this->Benchmark($start);
          return $arr;
        }
      }
    }

    if (preg_match('/^https:/', $url)) {
      if (empty($this->ca_file)) {
        throw new Exception('Empty property ca_file');
      }
      if (!file_exists($this->ca_file)) {
        throw new Exception('Unable to read file '.$this->ca_file);
      }
    }

    $ch = curl_init($url);
    if ($ch == false) {
      return false;
    }

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,  $method);

    if ($method == 'GET') {
      curl_setopt($ch, CURLOPT_HTTPGET,        true);
      curl_setopt($ch, CURLOPT_ENCODING,       '');                  # This will create the 'Accept-Encoding' header
    }
    elseif ($method == 'POST') {
      $postStr = $this->Array2string($data);
      curl_setopt($ch, CURLOPT_POST,           true);
      curl_setopt($ch, CURLOPT_POSTFIELDS,     $postStr);
      curl_setopt($ch, CURLOPT_ENCODING,       '');                  # This will create the 'Accept-Encoding' header
    }
    elseif ($method == 'HEAD') {
      curl_setopt($ch, CURLOPT_NOBODY,         true);
    }

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER,         true);                  # Include headers in response
    curl_setopt($ch, CURLOPT_FORBID_REUSE,   true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout_sec);
    curl_setopt($ch, CURLOPT_USERAGENT,      $this->useragent);      # This will create the 'User-Agent' header

    if ($this->maxRedirects == 0) {
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);               # Don't follow redirects
    }
    elseif ($this->maxRedirects > 0) {
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);                # Follow redirects
      curl_setopt($ch, CURLOPT_MAXREDIRS,      $this->maxRedirects); # Limit number of redirects
    }

    if ($this->EnableCookies) {
      $cookieFile = $this->GetCookieFileName($url);
      curl_setopt($ch, CURLOPT_COOKIEJAR,    $cookieFile);
      curl_setopt($ch, CURLOPT_COOKIEFILE,   $cookieFile);
    }

    if (!empty($this->headers)) {
      curl_setopt($ch, CURLOPT_HTTPHEADER,   $this->headers);
    }

    if (preg_match('/^https:/', $url)) {
      curl_setopt($ch, CURLOPT_SSLVERSION,      6);                  # TLSv1.2
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,  true);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
      curl_setopt($ch, CURLOPT_CAINFO,          $this->ca_file);
      if (!empty($this->CipherString)) {
        curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, $this->CipherString);
      }
    }

    $res = curl_exec($ch);
    $err = curl_errno($ch);

    if ($err == 0) { # Success
      curl_close($ch);
      $headers = $this->getHeaders($res);
      $body    = $this->getBody($res);
      $status  = preg_replace('/^HTTP\/\d\.\d\ (\d{3})\ .+$/', '\\1', $headers['status']);
      $arr = array(
        'url'        => $url,
        'method'     => $method,
        'req_data'   => $postStr,
        'useragent'  => $this->useragent,
        'headers'    => $headers,
        'body'       => $body,
        'filename'   => '',
        'exectime'   => '',
        'cookiefile' => $cookieFile,
        'status'     => $status,
        'origin'     => 'new',
        'error'      => $this->curlErrorCode($err),
      );
      ######################################################
      # Cache only if status 200
      if ($status == '200' && $this->ForcedCacheMaxAge >= 0) {
        $cacheTime = $this->ParseCachingHeader($headers);
        if (!empty($this->ForcedCacheMaxAge) && $this->ForcedCacheMaxAge > $cacheTime) {
          $cacheTime = $this->ForcedCacheMaxAge;
        }
        if ($cacheTime > 0) {
          $ext = (string) $cacheTime;
          $filename = '/CURL_RESPON-'. $filenameHash .'.'. $ext;
          $arr['filename'] = $filename;
          $arr['exectime'] = $this->Benchmark($start);
          $this->FilePutContents($this->CacheDir . $filename, serialize($arr));
          return $arr;
        }
      }
      ######################################################
      $arr['exectime'] = $this->Benchmark($start);
      return $arr;
    }
    elseif ($err == 6 && $this->LoopCount <= $this->LoopLimit) { # Couldn't resolve host
      usleep(500000);
      return $this->Request($url, $method, $data);
    }

    $info = curl_getinfo($ch);
    curl_close($ch);
    if (!$this->debug) {
      return array(
        'url'        => $url,
        'method'     => $method,
        'req_data'   => $postStr,
        'useragent'  => $this->useragent,
        'headers'    => '',
        'body'       => '',
        'filename'   => '',
        'exectime'   => $this->Benchmark($start),
        'cookiefile' => $cookieFile,
        'status'     => '',
        'origin'     => 'new',
        'error'      => $this->curlErrorCode($err),
      );
    }
    throw new Exception('CURL ERROR No. '.$err.'. Details are --'                 . PHP_EOL . PHP_EOL .
      str_pad('ERROR ',            22, '.', STR_PAD_RIGHT) .' '. $this->curlErrorCode($err) . PHP_EOL .
      str_pad('Loop Count ',       22, '.', STR_PAD_RIGHT) .' '. $this->LoopCount           . PHP_EOL .
      str_pad('URL ',              22, '.', STR_PAD_RIGHT) .' '. $info['url']               . PHP_EOL .
      str_pad('HTTP Code ',        22, '.', STR_PAD_RIGHT) .' '. $info['http_code']         . PHP_EOL .
      str_pad('Connect Time ',     22, '.', STR_PAD_RIGHT) .' '. $info['connect_time']      . PHP_EOL .
      str_pad('Total Time ',       22, '.', STR_PAD_RIGHT) .' '. $info['total_time']        . PHP_EOL .
      str_pad('Name Lookup Time ', 22, '.', STR_PAD_RIGHT) .' '. $info['namelookup_time']   . PHP_EOL .
      str_pad('PHP Version ',      22, '.', STR_PAD_RIGHT) .' '. $this->getPHPversion()     . PHP_EOL . PHP_EOL
    );
  }
1117415
public static function post($url, $dataArray, $httpHeaders = array())
    {
        self::prepareRequest($httpHeaders, $dataArray);

        $response = CurlRequest::post($url, self::$postDataJSON, self::$httpHeaders);

        return self::processResponse($response);
    }
465557
private function handleHTTP()
    {
    	try
    	{
			$method = new ReflectionMethod($this->classname, $_REQUEST["svc"]);
    	}
    	catch (Exception $ex)
    	{
    		echo '{ error: "Method does not exists" }';
    		exit;
    	}
		if (!$method->isPublic())
		{
    		echo '{ error: "Method is not public" }';
			exit;
		}

		$params = $method->getParameters();
		$paramValues = array();
		$missingParams = array();
		foreach ($params as $param)
		{
			$paramName = $param->getName();
			$paramValue = ( isset($_REQUEST[$paramName]) ? $_REQUEST[$paramName] : null);
			if (is_null($paramValue) && $param->isDefaultValueAvailable())
			{
				$paramValue = $param->getDefaultValue();
			}
			if (is_null($paramValue))
			{
				$missingParams[] = $paramName;
			}
			else
			{
				$paramValues[$paramName] = $paramValue;
			}
		}
		if (count($missingParams) > 0)
		{
			echo '{ error: "Missing params", parameters: [ "' . implode('","', $missingParams) . '"] }';
		}
		else
		{
			try
			{
				$result = $method->invokeArgs($this, $paramValues);
				if (is_array($result))
				{
					echo json_encode($result);
				}
				elseif (is_object($result))
				{
					echo '{ error: "Return type is not supported" } ';
				}
				else
				{
					echo $result;
				}
			}
			catch (Exception $ex)
			{
				echo '{ error: "' . $ex->getMessage() . '" }';
			}
		}
    }
1367670
private function send($method, $url, array $data, array $headers, $cacheMinutes = 0, HttpExceptionHandler $handler = null)
    {
        if ($response = $this->getCachedResponse($method, $url, $data, $headers))
        {
            return $response;
        }

        try
        {
            // Execute the appropriate method on the Curl request class
            $curlResponse = $this->curl->$method($url, $data, $headers);
            // Convert the response
            $response = $this->responseParser->parse($curlResponse);

            $this->throwExceptionOnHttpErrors($response);
            $this->storeCachedResponse($response, $method, $url, $data, $headers, $cacheMinutes);

            return $response;
        }
        catch (CurlRequestException $exception)
        {
            $code = $exception->getCode();
            $message = $exception->getMessage();

            throw new RequestException($message, $code, $exception);
        }
        catch (HttpException $exception)
        {
            if ( ! $handler)
            {
                throw $exception;
            }

            return $handler->handleHttpException($exception);
        }
    }
331607
protected function doRequest($url, $method, $data, $contentType = null, $filePath = null)
  {
    if($method == 'FILE')
      $url = $this->uploadUrl . $url;
    else
      $url = $this->url . $url;

    if($this->debug){
      echo "URL: $url\n";
      echo "Data: " . print_r($data, true) . "\n";
    }

    $c = curl_init();

    curl_setopt($c, CURLOPT_VERBOSE, $this->debug);

    if($this->username && $this->password){
      curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
      curl_setopt($c, CURLOPT_USERPWD, "$this->username:$this->password");
    }

    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($c, CURLOPT_USERAGENT, "tan-tan.github-api");
    curl_setopt($c, CURLOPT_TIMEOUT, $this->timeout);
    curl_setopt($c, CURLOPT_HEADER, true);
    curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);

    if(is_array($data)){
      foreach($data as $key => $value){
        if(is_bool($value))
          $data[$key] = $value ? 'true' : 'false';
      }
    }

    switch($method){
      case 'FILE':
        curl_setopt($c, CURLOPT_HTTPHEADER, array("Content-type: $contentType"));
        curl_setopt($c, CURLOPT_POST, true);
        curl_setopt($c, CURLOPT_POSTFIELDS, file_get_contents($filePath));

        if(count($data))
          $url .= '?' . http_build_query($data);
        break;

      case 'GET':
        curl_setopt($c, CURLOPT_HTTPGET, true);
        if(count($data))
          $url .= '?' . http_build_query($data);
        break;

      case 'POST':
        curl_setopt($c, CURLOPT_POST, true);
        if(count($data))
          curl_setopt($c, CURLOPT_POSTFIELDS, $data);
        break;

      case 'PUT':
        curl_setopt($c, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($c, CURLOPT_PUT, true);

        $headers = array('X-HTTP-Method-Override: PUT', 'Content-type: application/x-www-form-urlencoded');

        if(count($data)){
          $content = json_encode($data, JSON_FORCE_OBJECT);

          $fileName = tempnam(sys_get_temp_dir(), 'gitPut');
          file_put_contents($fileName, $content);

          $f = fopen($fileName, 'rb');
          curl_setopt($c, CURLOPT_INFILE, $f);
          curl_setopt($c, CURLOPT_INFILESIZE, strlen($content));
        }
        curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
        break;

      case 'PATCH':
      case 'DELETE':
        curl_setopt($c, CURLOPT_CUSTOMREQUEST, $method);

        if($data){
          curl_setopt($c, CURLOPT_POST, true);
          curl_setopt($c, CURLOPT_POSTFIELDS, $data);
        }
        break;
    }

    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);

    $response = curl_exec($c);

    curl_close($c);

    if($this->debug)
      echo "Response:\n$response\n";

    return $response;
  }
582917
public function send($url, $method = 'GET', $data = [])
    {
        $method = strtolower($method);

        $settings = [
            'headers'  => array_merge([
                'Authorization' => 'Bearer ' . $this->getToken(),
                'Content-Type' => 'application/x-www-form-urlencoded',
            ], $this->getHeaders()),
        ];

        if ($method == 'post') {
            $settings['form_params'] = $data;
        }

        return $this->client
            ->$method($url, $settings);
    }
198868
public function post($url, array $query = [], array $data = [], array $files = [])
    {
        $url = $this->buildUrl($url, $query);

        if ($files) {
            foreach ($files as $key => $file) {
                $data[$key] = new CURLFile($file['tmp_name']);
            }
        } else {
            $data = http_build_query($data);
        }

        $handle = $this->getHandler();

        curl_setopt_array($handle, [
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $data,
        ]);

        return $this->run($handle, $url);
    }
639841
public function request($method, $url, $params = null, $version = null, $headers = null)
    {
        $params = $params ?: [];
        $headers = $headers ?: [];
        if ($this->accessToken && $this->tokenType === 'Bearer') {
            $headers['Authorization'] = 'Bearer ' . $this->accessToken;
        }

        $payloadType = strcasecmp($method, 'get') === 0 ? 'query' : 'json';
        $client = $this->httpClient();

        if (!$this->noVersion) {
            $url = Sumup::getApiVersion() . '/' . $url;
        }

        try {
            $response = $client->request($method, $url, [
                $payloadType => $params,
                'headers' => $headers,
                'http_errors' => false
            ]);
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            throw new Error\ApiRequestorError($e->getMessage());
        }

        return new ApiResponse($response);
    }
268430
public function get($url, $data = [], $method = 'post') {

        $ch = curl_init($this->gitlab_host . '/api/v3' . $url);
       
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'PRIVATE-TOKEN:' . $this->private_key
        ));
        if($this->debug){
            curl_setopt($ch, CURLOPT_VERBOSE, true);
            if(!\sb\Gateway::$command_line){
                $curl_log = fopen("php://temp", 'rw');
                curl_setopt($ch, CURLOPT_STDERR, $curl_log);
            }
            
        }
         
       
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        if ($data) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            if ($method != 'post') {
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
            }
        }

        $error = curl_error($ch);
        $error_no = curl_errno($ch);
      
        if ($error_no) {
            throw(new \Exception($error . ': ' . $error_no));
        }
        $data = json_decode(curl_exec($ch));
        
        if($this->debug && !\sb\Gateway::$command_line){
            rewind($curl_log);
            $output= fread($curl_log, 2048);
            echo "<pre>". print_r($output, 1). "</pre>";
            fclose($curl_log);

        }
        
        return $data;
    }
1137398
static function FilePost($url, $data = "", $verify_cert = false, $timeout = 30)
	{
		$qs = HttpRequest::ArrayToQueryString($data);
		$url = $url . ($qs ? "?" . $qs : "");

		$show_headers = false;
		$url = parse_url($url);

		if (!isset($url['port'])) {
			if ($url['scheme'] == 'http') { $url['port']=80; }
			elseif ($url['scheme'] == 'https') { $url['port']=443; }
		}
		$url['query']=isset($url['query'])?$url['query']:'';

		$url['protocol']=$url['scheme'].'://';
		$eol="\r\n";

		$headers =  "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol.
			"Host: ".$url['host'].$eol.
			"Referer: ".$url['protocol'].$url['host'].$url['path'].$eol.
			"Content-Type: application/x-www-form-urlencoded".$eol.
			"Content-Length: ".strlen($url['query']).$eol.
			$eol.$url['query'];
		$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
		if($fp)
		{
			fputs($fp, $headers);
			$result = '';
			while(!feof($fp)) { $result .= fgets($fp, 128); }
			fclose($fp);
			if (!$show_headers)
			{
				//removes headers
				$match = preg_split("/\r\n\r\n/s",$result,2);
				$result = $match[1];
			}

			return $result;
		}
	}
906283
private function exec($url, $data = '', $method = 'post', $header = [])
    {
        $res = false;
        $this->try = 0;
        $this->result = '';
        $this->action('start');

        while ($this->try < $this->tryMax) {
            $this->try++;
            $res = $this->realExec($url, $data, $method, $header);
            if ($res) {
                break;
            }
        }

        $this->action('stop');
        return $res;
    }
218825
private function request($method, $uri, $data = [])
    {
        $uri = $this->getUri($uri);

        $headers = [];

        // Basic Auth
        $credentials = $this->key.':'.$this->password;

        // User Agent
        $agent = sprintf("%s %s", Client::NAME, Client::VERSION);

        $ch = curl_init();

        if (strtoupper($method) === 'GET' && !empty($data)) {
            $queryString = http_build_query($data);
            $uri .= '?'.$queryString;
        }

        $options = [
            CURLOPT_URL => $uri,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_USERAGENT => $agent,
            CURLOPT_USERPWD => $credentials,
            CURLOPT_TIMEOUT => 60,
        ];

        if (strtoupper($method) === 'POST') {
            $jsonData = json_encode($data);

            $headers[] = 'Content-Type: application/json';
            $headers[] = 'Content-Length: '.strlen($jsonData);

            $options[CURLOPT_CUSTOMREQUEST] = 'POST';
            $options[CURLOPT_POSTFIELDS] = $jsonData;
        }

        if (isset($this->version) && is_numeric($this->version)) {
            $headers[] = 'X-EWAY-APIVERSION: '.$this->version;
        }

        $options[CURLOPT_HTTPHEADER] = $headers;

        curl_setopt_array($ch, $options);

        $rawResponse = curl_exec($ch);

        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

        if (curl_errno($ch)) {
            $responseError = curl_error($ch);
            $responseBody = '';
        } else {
            $responseError = '';
            $responseBody = $this->parseResponse($rawResponse, $headerSize);
        }

        $response = new Response($statusCode, $responseBody, $responseError);

        curl_close($ch);

        return $response;
    }
1035901
public function request($method, array $params = [])
    {
        $client = new \GuzzleHttp\Client();

        $multipartParams = [];
        foreach ($params as $key => $value) {
            $multipartParams[] = [
                'name' => $key,
                'contents' => is_scalar($value) ? (string)$value : $value
            ];
        }

        try {
            $response = $client->post($this->getUrl($method), [
                'verify' => false,
                'multipart' => $multipartParams ?: null
            ]);
            $response = json_decode($response->getBody());

            if ($response === null) {
                throw new HttpRuntimeException('Empty response.');
            }
            return new Response($response->ok, $response->result);
        } catch (ClientException $e) {
            $response = json_decode($e->getResponse()->getBody()->getContents());
            return new Response($response->ok, null, $response->error_code, $response->description);
        } catch (ServerException $e) {
            return new Response(false, null, $e->getResponse()->getStatusCode(), $e->getResponse()->getReasonPhrase());
        }
    }