直接下载文件
@param string $fileName 保存路径
@param string $url 下载文件地址
@param array $requestBody 发送内容，可以是字符串、数组，如果为空则取content属性值
@param string $method 请求方法，GET、POST等，一般用GET
@return Response
354178
public function download($fileName, $url = null, $requestBody = null, $method = 'GET')
    {
        $result = $this->saveFile($fileName)->send($url, $requestBody, $method);
        $this->saveFileOption = array();
        return $result;
    }
1213833
public function rest($method, $url, $body = null, $headers = [], $options = [])
    {
        if (isset($headers['Content-Type']) && strpos($headers['Content-Type'], '/json') === false) {
            throw new InvalidValueException(['Content-Type of rest is not application/json: :content-type', 'content-type' => $headers['Content-Type']]);
        } else {
            $headers['Content-Type'] = 'application/json';
        }

        if (!isset($headers['X-Requested-With'])) {
            $headers['X-Requested-With'] = 'XMLHttpRequest';
        }

        if (!isset($headers['Accept'])) {
            $headers['Accept'] = 'application/json';
        }

        if (is_array($body)) {
            $body = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }

        $response = $this->request($method, $url, $body, $headers, $options);

        if (!is_array($response->body)) {
            if (strpos($response->content_type, '/json') === false) {
                throw new ContentTypeException(['content-type of response is not application/json: :content-type => `:url`',
                    'content-type' => $response->content_type,
                    'url' => $response->url],
                    $response);
            }

            throw new JsonDecodeException(['json decode failed: `:url`', 'url' => $response->url], $response);
        }

        return $response;
    }
1020630
public function getResponse($id, $filename = null, $forceDownload = false)
	{
		$object = $this->container->get($id);

		if ($filename === null)
		{
			$filename = $object->getBasename();
		}

		if (!pathinfo($filename, PATHINFO_EXTENSION) && $object->getExtension())
		{
			$filename .= '.'. $object->getExtension();
		}

		/** @var HttpResponse $response */
		$response = $this->controller->getResponse();

		$response->setContent(new LazyResponse($object));
		$response->getHeaders()->addHeaders(array(
			'Content-Type' => $object->getContentType() ?: 'application/octet-stream',
			'Content-Disposition' => ($forceDownload ? 'attachment' : 'inline') .';filename="'. str_replace('"', '\\"', $filename) .'"',
			'Content-Transfer-Encoding' => 'binary',
			'Expires' => '-1 year',
			'Cache-Control' => 'must-revalidate',
			'Pragma' => 'public',
			'Content-Length' => $object->getContentLength(),
		));

		return $response;
	}
175904
public function get(
        string $url,
        string $method,
        array $query = [],
        array $body = [],
        array $server = []
    ): array {
        $method = strtolower($method);
        $requestParts = $this->buildRequestParts(
            $url,
            $query,
            $body,
            $server
        );

        return $this->tryRequest(function () use ($method, $requestParts) {
            return $this
                ->httpAdapter
                ->getByRequestParts(
                    $this->host,
                    $method,
                    $requestParts
                );
        }, $this
            ->retryMap
            ->getRetry(
                $url,
                $method
            )
        );
    }
697244
static function get_url_and_save($fully_qualified_url, $filename)
    {
        // strange 400 errors can occur if we don't check to make sure our URL is trimmed up.
        $fully_qualified_url = trim($fully_qualified_url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $fully_qualified_url);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        $output = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpdebug = curl_getinfo($ch);
        if ($httpcode == 200) {
            self::create_file($filename, $output);
            echo("Saved file: ".$filename.PHP_EOL);
        } else {
            echo ('error.  http debug: '.var_export($httpdebug, true).PHP_EOL);
        }
        curl_close($ch);
    }
723925
public function handle(string $method, $body = false, $uriAppend = false, array $queryParams = [])
    {
        $clientBuilder = new ClientBuilder();
        $url           = HttpHelper::setHttPortToUrl($this->client->getGatewayUrl(), false) . '/' . $this->resource->getVersion() . '/' . $this->resource->getURI();
        $client = $clientBuilder->setConnectionParams(['client' => ['headers' => $this->setAuthorization()]])
                                ->setHosts(['host' => $url])
                                ->build();

        try {

            $size = $queryParams['body']['size'] ?? 0;
            $from = $queryParams['body']['from'] ?? 0;

            $response = new ElasticSearchResponse($this->multi ? $client->msearch($queryParams) : $client->search($queryParams), $this->multi, $size, $from);
        } catch (\Exception $ex) {
            $error = json_decode($ex->getMessage());
            throw new \Exception($error->error->reason ?? $ex->getMessage());
        }

        return $response;
    }
583320
public function handle(string $method, $body = false, $uriAppend = false, array $queryParams = [])
    {
        $client   = $this->createElasticClient();
        $param    = $queryParams[0];
        $endPoint = "search";

        if (is_a($param, Search::class)) {
            $endPoint    = "search";
            $queryParams = $param->getParams();

        } elseif (is_a($param, MSearch::class)) {
            $endPoint    = "msearch";
            $queryParams = $param->getParams();
        }

        try {
            $elasticData = $client->{$endPoint}($queryParams);

            if ($client->transport->getLastConnection()) {
                $elasticData['debug'] = $client->transport->getLastConnection()->getLastRequestInfo();
            }

            if ($endPoint == 'msearch') {
                foreach ($elasticData['responses'] as $key => $responseItem) {
                    $responseItem['debug'] = $elasticData['debug'];
                    $response[]            = new Response($responseItem);
                }
            } else {
                $response = new Response($elasticData, $queryParams['body']['size'] ?? 0, $queryParams['body']['from'] ?? 0);
            }
        } catch (\Exception $ex) {
            $error = json_decode($ex->getMessage());
            throw new \Exception($error->error->reason ?? $ex->getMessage());
        }

        return $response;
    }
708656
private function getResponse($method, $path, $body = null, $headers = [])
    {
        $allHeaders = array_merge($this->getAuthorizationHeader(), $headers);
        $uri = $path;

        $request = new Request($method, $uri, $allHeaders, $body);

        return $this->guzzle->send($request);
    }
307682
private function request($method, $url, $params = [])
    {
        $this->getLogger()->debug('Creating a new request with received parameters');
        $options = [
            'headers' => null, 'body' => null
        ];
        // Multipart
        if (array_key_exists('multipart', $params)) {
            // Build the multipart message
            $options['body'] = new MultipartStream($params['multipart']);
        } else if (array_key_exists('json', $params)) {
            // Build the JSON body and content type
            $options['body'] = json_encode($params['json']);
            $options['headers'] = ['content-type' => 'application/json'];
        } else if ($method == 'POST' || $method == 'PUT' || $method == 'DELETE') {
            $options['headers'] = ['content-type' => 'application/x-www-form-urlencoded'];
            if (count($params) > 0) {
                $options['body'] = http_build_query($params, null, '&');
            }
        }
        $this->logger->debug('Getting Authenticated Request');
        $request = $this->provider->getAuthenticatedRequest($method, $this->provider->getCmsApiUrl() . rtrim($url, '/'), $this->getAccessToken(), $options);
        $this->logger->debug('Getting parsed response from Abstract Provider');
        return $this->provider->getParsedResponse($request);
    }
827507
private function responseHandler($requestMethod, $requestPath, array $clientResponse)
    {
        $statusCode = (int) $clientResponse[0];
        $responseString = (string) $clientResponse[1];

        try {
            $responseData = Json::decode($responseString);
            $this->validateClientResponse($requestMethod, $requestPath, $statusCode, $responseData);

            if (400 <= $statusCode) {
                // either we sent an incorrect request, or there is a server error
                throw new HttpClientException(sprintf('[%d] %s "%s/%s": %s', $statusCode, $requestMethod, $this->baseUri, $requestPath, $responseData['error']));
            }

            // the request was correct, and there was not a server error
            if ($responseData[$requestPath]['ok']) {
                // our request was handled correctly
                if (!\array_key_exists('data', $responseData[$requestPath])) {
                    return null;
                }

                return $responseData[$requestPath]['data'];
            }

            // our request was not handled correctly, something went wrong...
            throw new ApiException($responseData[$requestPath]['error']);
        } catch (JsonException $e) {
            // unable to parse the JSON
            throw new HttpClientException(sprintf('[%d] %s "%s/%s": %s', $statusCode, $requestMethod, $this->baseUri, $requestPath, $e->getMessage()));
        }
    }
1119603
public function request($method, $url, $params = array(), $xml = "", $format = "")
	{
		if ( !$format) $format = $this->format;

		$response = $this->api->request($method, $url, $params, $xml, $format);
		return $this->parseResponse($response);
	}
498803
public function create($uri, $method = 'GET', $params = [], $cookie = [], $files = [], $server = [], $content = null)
    {
        $server['PATH_INFO']      = '';
        $server['REQUEST_METHOD'] = strtoupper($method);
        $info                     = parse_url($uri);
        if (isset($info['host'])) {
            $server['SERVER_NAME'] = $info['host'];
            $server['HTTP_HOST']   = $info['host'];
        }
        if (isset($info['scheme'])) {
            if ('https' === $info['scheme']) {
                $server['HTTPS']       = 'on';
                $server['SERVER_PORT'] = 443;
            } else {
                unset($server['HTTPS']);
                $server['SERVER_PORT'] = 80;
            }
        }
        if (isset($info['port'])) {
            $server['SERVER_PORT'] = $info['port'];
            $server['HTTP_HOST']   = $server['HTTP_HOST'] . ':' . $info['port'];
        }
        if (isset($info['user'])) {
            $server['PHP_AUTH_USER'] = $info['user'];
        }
        if (isset($info['pass'])) {
            $server['PHP_AUTH_PW'] = $info['pass'];
        }
        if (!isset($info['path'])) {
            $info['path'] = '/';
        }
        $options                      = [];
        $options[strtolower($method)] = $params;
        $queryString                  = '';
        if (isset($info['query'])) {
            parse_str(html_entity_decode($info['query']), $query);
            if (!empty($params)) {
                $params      = array_replace($query, $params);
                $queryString = http_build_query($query, '', '&');
            } else {
                $params      = $query;
                $queryString = $info['query'];
            }
        } elseif (!empty($params)) {
            $queryString = http_build_query($params, '', '&');
        }
        if ($queryString) {
            parse_str($queryString, $get);
            $options['get'] = isset($options['get']) ? array_merge($get, $options['get']) : $get;
        }

        $server['REQUEST_URI']  = $info['path'] . ('' !== $queryString ? '?' . $queryString : '');
        $server['QUERY_STRING'] = $queryString;
        $options['cookie']      = $cookie;
        $options['param']       = $params;
        $options['file']        = $files;
        $options['server']      = $server;
        $options['url']         = $server['REQUEST_URI'];
        $options['baseUrl']     = $info['path'];
        $options['pathinfo']    = '/' == $info['path'] ? '/' : ltrim($info['path'], '/');
        $options['method']      = $server['REQUEST_METHOD'];
        $options['domain']      = isset($info['scheme']) ? $info['scheme'] . '://' . $server['HTTP_HOST'] : '';
        $options['content']     = $content;
        foreach ($options as $name => $item) {
            if (property_exists($this, $name)) {
                $this->$name = $item;
            }
        }
        return $this;
    }
1098488
public function methodMatch($methods, $requestMethod, Request $request)
    {
        $match = false;
        if ($requestMethod === null) {
            $requestMethod = ($request->getRequestMethod()) ? $request->getRequestMethod() : 'GET';
        }
        $methods = explode('|', $methods);
        foreach ($methods as $method) {
            if (strcasecmp($requestMethod, $method) === 0) {
                $match = true;
                break;
            } else {
                continue;
            }
        }
        if ($match === true) {
            return true;
        }

        return false;
    }
891582
protected function makeHttpRequest($url, $method, $headers, $body = null) {
    $request_headers = array_merge($headers, self::$api_version_header);

    $result = $this->doHttpRequest($url,
                                   $method,
                                   $request_headers,
                                   $body);

    if ($result === false) {
      return false;
    }

    return [
      'status_code' => $result['status_code'],
      'headers' => $result['headers'],
      'body' => $result['body'],
    ];
  }
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
    );
  }
404944
public function request($url, $method = 'GET', $options = []): ResponseInterface
    {
        $method = strtoupper($method);

        $options = array_merge(self::$defaults, $options, ['handler' => $this->getHandlerStack()]);

        $options = $this->fixJsonIssue($options);

        if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) {
            $options['base_uri'] = $this->baseUri;
        }

        $response = $this->getHttpClient()->request($method, $url, $options);
        $response->getBody()->rewind();

        return $response;
    }
356983
public function createRequest($url, $method = 'GET', array $headers = [], $body = null)
    {
        $headers = array_merge($headers, ['User-Agent' => strval($this->userAgent)]);
        return new Request($method, $url, $headers, $body);
    }