发起一个HTTP/HTTPS的请求

@param string $url     接口的URL
@param string $method  请求类型   GET | POST
@param array  $params  接口参数
@param array  $options 其它选项
@param int    $retry   重试次数

@return array | boolean
194010
public function request($url, $method = self::GET, $params = array(), $options = array(), $retry = 1)
    {
        if ($this->token) {
            $url = preg_replace('/[\?&]access_token=.*?/i', '', $url);
            $url .= (stripos($url, '?') ? '&' : '?').'access_token='. $this->token->getToken();
        }

        $method = strtoupper($method);

        if ($this->json) {
            $options['json'] = true;
        }

        $response = parent::request($url, $method, $params, $options);

        $this->json = false;

        if (empty($response['data'])) {
            throw new Exception('服务器无响应');
        }

        if (!preg_match('/^[\[\{]\"/', $response['data'])) {
            return $response['data'];
        }

        $contents = json_decode($response['data'], true);

        // while the response is an invalid JSON structure, returned the source data
        if (JSON_ERROR_NONE !== json_last_error()) {
            return $response['data'];
        }

        if (isset($contents['errcode']) && 0 !== $contents['errcode']) {
            if (empty($contents['errmsg'])) {
                $contents['errmsg'] = 'Unknown';
            }

            // access token 超时重试处理
            if ($this->token && in_array($contents['errcode'], array('40001', '42001')) && $retry > 0) {
                // force refresh
                $this->token->getToken(true);

                return $this->request($url, $method, $params, $options, --$retry);
            }

            throw new Exception("[{$contents['errcode']}] ".$contents['errmsg'], $contents['errcode']);
        }

        if ($contents === array('errcode' => '0', 'errmsg' => 'ok')) {
            return true;
        }

        return $contents;
    }
824167
protected function sendRequest(string $method, string $uri, array $options = []): array
    {
        $request = $this->client->createRequest($method, $uri);

        $key = $method === Api::GET ? 'query' : 'form_params';
        $options[$key] = $this->signRequest(
            $method,
            $request->getUri()->__toString(),
            $options[$key] ?? []
        );

        return $this->processResponse(
            $this->client->send($request, $options)
        );
    }
960953
public function request($method, $url, $options)
    {
        $request = $this->authClient->getAuthenticatedRequest($method, $url, $this->getAccessToken());

        return $this->httpClient->send($request, $options);
    }
361837
public function request($method, $url, $body = null, $headers = [], $options = [])
    {
        if (is_array($url)) {
            if (count($url) > 1) {
                $uri = $url[0];
                unset($url[0]);
                $url = $uri . (strpos($uri, '?') !== false ? '&' : '?') . http_build_query($url);
            } else {
                $url = $url[0];
            }
        }

        if (preg_match('/^http(s)?:\/\//i', $url) !== 1) {
            throw new NotSupportedException(['only HTTP requests can be handled: `:url`', 'url' => $url]);
        }

        if (is_string($headers)) {
            $headers = [strpos($headers, '://') ? 'Referer' : 'User-Agent' => $headers];
        }

        if (isset($headers['-'])) {
            $headers['Referer'] = $headers['-'];
            unset($headers['-']);
        }

        if (isset($headers['Referer'])) {
            if (is_array($headers['Referer'])) {
                $referer = $headers['Referer'];
                if (isset($referer[0])) {
                    $str = $referer[0];
                    unset($referer[0]);
                } else {
                    $str = 'http://TRACK/';
                }
                $headers['Referer'] = $str . (strpos($str, '?') ? '&' : '?') . http_build_query($referer);
            } elseif (!strpos($options['Referer'], '://')) {
                $headers['Referer'] = 'http://TRACE/' . $headers['Referer'];
            }
        }

        if (!isset($headers['User-Agent'])) {
            $headers['User-Agent'] = self::USER_AGENT_IE;
        }

        if (is_int($options) || is_float($options)) {
            $options = ['timeout' => $options];
        }

        if (!isset($options['timeout'])) {
            $options['timeout'] = $this->_timeout;
        }

        if ($this->_proxy && !isset($options['proxy'])) {
            $options['proxy'] = $this->_proxy;
        }

        if ($this->_cafile && !isset($options['cafile'])) {
            $options['cafile'] = $this->_cafile;
        }

        $options['verify_peer'] = $this->_verify_peer;

        $request = new Request();
        $request->method = $method;
        $request->url = $url;
        $request->headers = $headers;
        $request->body = $body;
        $request->options = $options;

        $this->logger->debug($request, 'httpClient.request');

        $this->eventsManager->fireEvent('httpClient:beforeRequest', $this, $request);
        $response = $this->do_request($request);
        if (strpos($response->content_type, '/json') !== false && $json = json_decode($response->body, true)) {
            $response->body = $json;
        }
        $this->eventsManager->fireEvent('httpClient:afterRequest', $this, $response);
        $response->request = $request;
        $response->user_data = isset($options['user_data']) ? $options['user_data'] : null;

        $this->logger->debug($response, 'httpClient.response');

        if ($response->http_code === 429) {
            throw new TooManyRequestsException($response->url, $response);
        } elseif ($response->http_code === 403) {
            throw new ForbiddenException($response->url, $response);
        } elseif ($response->http_code === 401) {
            throw new UnauthorizedException($response->url, $response);
        }

        if ($response->http_code >= 500) {
            throw new ServiceUnavailableException(['service is unavailable: :http_code => `:url`',
                'http_code' => $response->http_code,
                'url' => $response->url], $response);
        }

        if ($response->http_code >= 400) {
            throw new BadRequestException(['bad request: :http_code => `:url`', 'http_code' => $response->http_code, 'url' => $response->url], $response);
        }

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

        return json_decode($response->getBody(), true);
    }
1132113
protected function parseHttpResult($url, $params, $method, $force = true)
    {
        if (stripos($url, 'http://') === false && stripos($url, 'https://') === false) {
            $url = self::WECHAT_BASE_URL . $url;
        }
        $return = $this->http($url, $params, $method);
        $return = json_decode($return, true) ? : $return;
        if (isset($return['errcode']) && $return['errcode']) {
            $this->lastErrorInfo = $return;
            $log = [
                'class' => __METHOD__,
                'arguments' => func_get_args(),
                'result' => $return,
            ];
            switch ($return['errcode']) {
                case 40001: //access_token 失效,强制更新access_token, 并更新地址重新执行请求
                    if ($force) {
                        Yii::warning($log, 'wechat.sdk');
                        $url = preg_replace_callback("/access_token=([^&]*)/i", function(){
                            return 'access_token=' . $this->getAccessToken(true);
                        }, $url);
                        $return = $this->parseHttpResult($url, $params, $method, false); // 仅重新获取一次,否则容易死循环
                    }
                    break;
            }
            Yii::error($log, 'wechat.sdk');
        }
        return $return;
    }
965389
public function get($url, array $params = null, array $options = array())
	{
		return $this->request($url, 'GET', $params, $options);
	}
786130
protected function request($url, $method = self::GET, $params = array(), $options = array())
    {
        if ($method === self::GET || $method === self::DELETE) {
            $url .= (stripos($url, '?') ? '&' : '?').http_build_query($params);
            $params = array();
        }

        curl_setopt($this->curl, CURLOPT_HEADER, 1);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($this->curl, CURLOPT_URL, $url);

        //使用证书情况
        if (isset($options['sslcert_path']) && isset($options['sslkey_path'])) {
            if (!file_exists($options['sslcert_path']) || !file_exists($options['sslkey_path'])) {
                throw new \Exception('Certfile is not correct');
            }
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, 2);//严格校验
            curl_setopt($this->curl, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($this->curl, CURLOPT_SSLCERT, $options['sslcert_path']);
            curl_setopt($this->curl, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($this->curl, CURLOPT_SSLKEY, $options['sslkey_path']);
        } else {
            curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, 0);
        }

        // Check for files
        if (isset($options['files']) && count($options['files'])) {
            foreach ($options['files'] as $index => $file) {
                $params[$index] = $this->createCurlFile($file);
            }

            version_compare(PHP_VERSION, '5.5', '>') || curl_setopt($this->curl, CURLOPT_SAFE_UPLOAD, false);

            curl_setopt($this->curl, CURLOPT_POST, 1);
            curl_setopt($this->curl, CURLOPT_POSTFIELDS, $params);
        } else {
            if (isset($options['json'])) {
                $params = JSON::encode($params);
                $options['headers'][] = 'content-type:application/json';
            }

            curl_setopt($this->curl, CURLOPT_POSTFIELDS, $params);
        }

        // Check for custom headers
        if (isset($options['headers']) && count($options['headers'])) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $options['headers']);
        }

        // Check for basic auth
        if (isset($options['auth']['type']) && 'basic' === $options['auth']['type']) {
            curl_setopt($this->curl, CURLOPT_USERPWD, $options['auth']['username'].':'.$options['auth']['password']);
        }

        $response = $this->doCurl();

        // Separate headers and body
        $headerSize = $response['curl_info']['header_size'];
        $header = substr($response['response'], 0, $headerSize);
        $body = substr($response['response'], $headerSize);

        $results = array(
                    'curl_info' => $response['curl_info'],
                    'content_type' => $response['curl_info']['content_type'],
                    'status' => $response['curl_info']['http_code'],
                    'headers' => $this->splitHeaders($header),
                    'data' => $body,
                   );

        return $results;
    }
279264
public function commit($method, $url, $params = [], $options = [])
    {
        $userAgent = [
            'bindings_version' => $this->config['version'],
            'lang'             => 'php',
            'lang_version'     => phpversion(),
            'publisher'        => 'conekta',
            'uname'            => php_uname(),
        ];

        $request = [
            'exceptions'      => false,
            'timeout'         => '80',
            'connect_timeout' => '30',
            'headers'         => [
                'Accept'                      => "application/vnd.conekta-v{$this->config['version']}+json",
                'Accept-Language'             => $this->config['locale'],
                'Authorization'               => 'Basic '.base64_encode($this->config['private_key'].':'),
                'Content-Type'                => 'application/json',
                'RaiseHtmlError'              => 'false',
                'X-Conekta-Client-User-Agent' => json_encode($userAgent),
                'User-Agent'                  => 'Conekta PayMeBindings/'.$this->config['version'],
            ],
        ];

        if (!empty($params)) {
            $request[$method === 'get' ? 'query' : 'json'] = $params;
        }

        $rawResponse = $this->getHttpClient()->{$method}($url, $request);
        $statusCode = $rawResponse->getStatusCode();

        $response = $statusCode == 200
            ? $this->parseResponse($rawResponse->getBody())
            : $this->responseError($rawResponse->getBody(), $statusCode);

        return $this->respond($response);
    }
1277362
private function privateRequest($url, $params = [], $method = 'GET')
    {
        // build the POST data string
        $params['timestamp']  = number_format((microtime(true) * 1000), 0, '.', '');
        $params['recvWindow'] = $this->recvWindow;

        $query   = http_build_query($params, '', '&');

        // set API key and sign the message
        $sign    = hash_hmac('sha256', $query, $this->secret);

        $headers = array(
            'X-MBX-APIKEY: ' . $this->key
        );

        // make request
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
   
         // build the POST data string
        $postdata = $params;

        // Set URL & Header
        curl_setopt($this->curl, CURLOPT_URL, $this->url . $url."?{$query}&signature={$sign}");

        //Add post vars
        if($method == "POST") {
            curl_setopt($this->curl,CURLOPT_POST, 1);
            curl_setopt($this->curl, CURLOPT_POSTFIELDS, array());
        }

        //Get result
        $result = curl_exec($this->curl);
        if($result === false)
            throw new \Exception('CURL error: ' . curl_error($this->curl));

         // decode results
        $result = json_decode($result, true);
        if(!is_array($result) || json_last_error())
            throw new \Exception('JSON decode error');

        return $result;

    }
1168191
protected function request($uri, array $params = [], array $options = [])
    {
        if ($options) {
            $params = array_merge($params, $options);
        }
        // 没有参数, 设置一个默认参数
        if (!$params) {
            $params['php-etcd-client'] = 1;
        }
        $data = [
            'json' => $params,
        ];
        if ($this->token) {
            $data['headers'] = ['Grpc-Metadata-Token' => $this->token];
        }

        $response = $this->getHttpClient()->request('post', $uri, $data);
        $content = $response->getBody()->getContents();

        $body = json_decode($content, true);
        if ($this->pretty && isset($body['header'])) {
            unset($body['header']);
        }

        return $body;
    }
301050
protected function request($api, array $params, $method = 'post', array $options = [], $returnResponse = false)
    {
        $params = array_merge($params, $this->merchant->only(['sub_appid', 'sub_mch_id']));

        $params['appid'] = $this->merchant->app_id;
        $params['mch_id'] = $this->merchant->merchant_id;
        $params['device_info'] = $this->merchant->device_info;
        $params['nonce_str'] = uniqid();
        $params = array_filter($params);
        $params['sign'] = generate_sign($params, $this->merchant->key, 'md5');

        $options = array_merge([
            'body' => XML::build($params),
        ], $options);

        $response = $this->getHttp()->request($api, $method, $options);

        return $returnResponse ? $response : $this->parseResponse($response);
    }
375417
public function sendRequest($url, $params, $method)
    {
        try{
            if (!empty($params['html'])){
                $commandName = 'GenerateFromHTML';
            }
            else if (!empty($params['url'])){
                $commandName = 'GenerateFromURL';
            }
            else if (!empty($params['file'])&& $url=='pdf'){
                $commandName = 'GenerateFromFile';
            }
            else {
                $operations = $this->getDescription()->getOperations();
                foreach ($operations as $operation)
                {
                    if ($operation->getUri()==$url && $operation->getHttpMethod() == $method)
                    {
                        $commandName = $operation->getName();
                    }
                }
            }
            $command = $this->getCommand($commandName, $params);
            $ret = $this->execute($command);

            if ( $commandName == 'GetAssetList' || $commandName == 'UploadAsset' )
            {
                return json_encode($ret);
            }
            return $ret->getBody(true);

        }catch(ClientErrorResponseException $exception){
            throw new \Exception($exception->getResponse()->getBody(true), $exception->getResponse()->getStatusCode());
        }
    }
1166575
public function commit($method, $url, $params = [], $options = [])
    {
        $request = $this->requestTemplate;

        $token = Arr::get($options, 'token');

        if (!$token) {
            // there are some methods that do not have $options argument
            $token = Arr::get($params, 'token');
            if ($token) {
                unset($params['token']);
            }
        }

        // on IPN we need to send content as form params
        $payloadKey = $method === 'post'
            ? (strpos($url, 'https://ipnpb.') === 0 ? 'form_params' : 'json')
            : 'query';

        $request['headers']['Authorization'] = "Bearer {$token}";
        $request[$payloadKey] = $params;

        $rawResponse = $this->getHttpClient()->$method($url, $request);

        $response = $this->responseToArray($rawResponse);

        $response = $this->respond($response, $params, $options, $rawResponse->getStatusCode());

        return $response;
    }
284516
public function commit($method, $url, $params = [], $options = [])
    {
        $request = [
            'exceptions'      => false,
            'timeout'         => '80',
            'connect_timeout' => '30',
            'headers'         => [
                'Content-Type'  => 'application/json',
                'User-Agent'    => 'MercadoPago PayMeBindings/'.$this->config['version'],
            ],
        ];

        if (!empty($params)) {
            $request[$method === 'get' ? 'query' : 'json'] = $params;
        }

        $authUrl = sprintf('%s?access_token=%s', $url, $this->config['private_key']);

        $rawResponse = $this->getHttpClient()->{$method}($authUrl, $request);

        $response = $this->parseResponse($rawResponse);

        return $this->respond($response, $rawResponse->getStatusCode());
    }
527940
protected function _request($method, $url, $params = [], $options = null)
    {
        $opts = $this->_opts->merge($options);
        list($resp, $options) = static::_staticRequest($method, $url, $params, $opts);
        $this->setLastResponse($resp);
        return [$resp->json, $options];
    }
1128559
public function send(string $method, string $url, array $options)
    {
        try {
            // Guzzle overwrites all query string values in the URI if queries are specified
            // in the 'query' option, so they need to be extracted first.
            $optionsPayload = $this->mergeOptions(
                ['query' => $this->parseQueryParams($url)],
                $options
            );

            $response = $this->buildClient()->request($method, $url, $optionsPayload);

            return $this->buildResponse($response);
        } catch (GuzzleException $exception) {
            // No "custom" exceptions, just rethrow whatever guzzle spits out.
            throw $exception;
        }
    }