Send an HTTP request.

@param RequestInterface $request Request to send
@param array            $options Request options to apply to the given
request and to the transfer.

@return ResponseInterface
@throws TransportException
324756
public function send(RequestInterface $request, array $options = [])
    {
        try {
            return $this->client->send($request, $options);
        } catch (TransferException $e) {
            throw new TransportException($e->getMessage(), $e->getCode(), $e);
        }
    }
693518
private function doSendRequest(RequestInterface $request)
    {
        try {
            $response = $this->getHttpClient()->sendRequest($request);
        } catch (HttpTransferException $e) {
            throw new TransferException(
                $e->getMessage(),
                $request,
                $e instanceof HttpException ? $e->getResponse() : null
            );
        }

        if ($response->getStatusCode() >= 400) {
            throw new InvalidResponseException('Bad response status code.', $request, $response);
        }

        $rawData = (string) $response->getBody();

        if (empty($rawData)) {
            return null;
        }

        $data = json_decode($rawData, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new InvalidResponseException('Could not decode the response.', $request, $response);
        }

        return $data;
    }
508968
public function execute(RequestInterface $request): ResponseInterface
    {
        $this->supports($request);

        if ($request instanceof InputInterface) {
            $request->validate();
        }

        $client = $this->getClient();

        $data = array_replace($request->toArray(), [
            'carrier' => $client->getCarrier(),
            'key'     => $client->getKey(),
        ]);

        $response = $client->call($this->getMethodName(), $data);

        return $this->parseResponse($response->getBody()->getContents());
    }
621410
public function requestAsync($method, $uri = '', array $options = [])
    {
        try {
            return $this->client->requestAsync($method, $uri, $options);
        } catch (TransferException $e) {
            throw new TransportException($e->getMessage(), $e->getCode(), $e);
        }
    }
913421
public function send(RequestInterface $request)
    {
        $apiResponse = null;

        try {
            $apiResponse = $this->loadResponse($request);

            if ($apiResponse->ok()) {
                return $apiResponse;
            } else {
                throw new Exception('Response has unsuccessful status');
            }
        } catch (Exception $e) {
            // The following means that request failed completely
            if (empty($apiResponse)) {
                $apiResponse = new ApiResponse($request);
            }

            throw new ApiException($apiResponse, $e);
        }
    }
1015901
public function sendRequest(RequestInterface $request)
    {
        if ($request instanceof InternalRequestInterface) {
            return $this->sendInternalRequest($request);
        }

        $protocolVersion = $this->getConfiguration()->getProtocolVersion();
        $this->getConfiguration()->setProtocolVersion($request->getProtocolVersion());

        $response = $this->send(
            $request->getUri(),
            $request->getMethod(),
            $request->getHeaders(),
            $request->getBody()
        );

        $this->getConfiguration()->setProtocolVersion($protocolVersion);

        return $response;
    }
1316945
private function query(RequestInterface $request)
    {
        return $this->client->send($request, array_merge(
            [RequestOptions::HTTP_ERRORS => false],
            $this->clientOptions
        ));
    }
465230
protected function doRequest(RequestInterface $request)
    {
        $ch = $this->createHandle($request);

        // Execute the request and close the connection.
        $content = curl_exec($ch);

        $error = curl_error($ch);

        if (!$this->getOption('allow_empty_result', false) && !trim((string) $content)) {
            // Error but nothing from cURL? Create our own
            $error = $error ?: 'No HTTP response received';

            throw new HttpRequestException($error, curl_errno($ch));
        }

        if (!$this->getOption('ignore_curl_error', false) && $error !== '') {
            throw new HttpRequestException($error, curl_errno($ch));
        }

        // Get the request information.
        $info = curl_getinfo($ch);

        // Close the connection.
        curl_close($ch);

        return $this->getResponse($content, $info);
    }
32417
protected function sendRequest(RequestInterface $request)
    {
        try {
            $response = $this->httpClient->send(
                $request,
                $this->getRequestOptions()
            );

            $this->multipartResources = [];

            return json_decode($response->getBody());
        } catch (RequestException $e) {
            $this->throwRequestException($e);
        }
    }
410331
public function send(TransportRequestInterface $request)
    {
        try {
            return new GuzzleTransportResponse($this->guzzleClient->send($request->getWrappedRequest()));
        } catch (\Exception $exception) {
            throw new TransportLayerException($exception->getMessage(), $exception->getCode(), $exception);
        }
    }
805939
public function send(RequestInterface $request)
	{
		$request = $this->authentication($request);
		$defaultHeaders = [
			'Accept'       => $this->getContentType(),
			'Content-Type' => $this->getContentType()
		];

		foreach ($defaultHeaders as $defaultHeader => $value)
		{
			if ( ! $request->hasHeader($defaultHeader))
			{
				$request = $request->withHeader($defaultHeader, $value);
			}
		}

		$response = $this->client->sendRequest($request);
		$response = $this->transformResponseToException($request, $response);

		return $response;
	}
279789
public function request(RequestInterface $request, array $options = []): HttpResultInterface
    {
        $options = $this->handleOptions(array_merge($this->defaultOptions, $options));

        $url = (string)$request->getUri();
        $profileKey = 'HttpClient.' . $url;

        App::profileStart($profileKey);

        list($host, $port) = $this->ipResolve($request, $options);

        $ssl = $request->getUri()->getScheme() === 'https';

        $client = new CoHttpClient($host, $port, $ssl);
        $this->applyOptions($client, $request, $options);
        $this->applyMethod($client, $request, $options);

        $path = $request->getUri()->getPath();
        $query = $request->getUri()->getQuery();
        if ($path === '') $path = '/';
        if ($query !== '') $path .= '?' . $query;

        $client->setDefer();
        $client->execute($path);

        App::profileEnd($profileKey);

        if (null !== $client->errCode && $client->errCode !== 0) {
            App::error(sprintf('HttpClient Request ERROR #%s url=%s', $client->errCode, $url));
            throw new RuntimeException(\socket_strerror($client->errCode), $client->errCode);
        }

        $result = new HttpCoResult(null, $client, $profileKey);
        return $result;
    }
886762
protected function onRejected(RequestInterface $request, array $options)
    {
        return function ($reason) use ($request, $options) {
            // If was bad response exception, test if we retry based on the response headers
            if ($reason instanceof BadResponseException) {
                if ($this->shouldRetryHttpResponse($options, $reason->getResponse())) {
                    return $this->doRetry($request, $options, $reason->getResponse());
                }
            // If this was a connection exception, test to see if we should retry based on connect timeout rules
            } elseif ($reason instanceof ConnectException) {
                // If was another type of exception, test if we should retry based on timeout rules
                if ($this->shouldRetryConnectException($reason, $options)) {
                    return $this->doRetry($request, $options);
                }
            }

            // If made it here, then we have decided not to retry the request
            return \GuzzleHttp\Promise\rejection_for($reason);
        };
    }
1214816
public function request(string $method, string $url, array $options = []): ResponseInterface
    {
        [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);

        if ($options['bindto'] && file_exists($options['bindto'])) {
            throw new TransportException(__CLASS__.' cannot bind to local Unix sockets, use e.g. CurlHttpClient instead.');
        }

        $options['body'] = self::getBodyAsString($options['body']);

        if ('' !== $options['body'] && 'POST' === $method && !isset($options['headers']['content-type'])) {
            $options['request_headers'][] = 'content-type: application/x-www-form-urlencoded';
        }

        if ($gzipEnabled = \extension_loaded('zlib') && !isset($options['headers']['accept-encoding'])) {
            // gzip is the most widely available algo, no need to deal with deflate
            $options['request_headers'][] = 'accept-encoding: gzip';
        }

        if ($options['peer_fingerprint']) {
            if (isset($options['peer_fingerprint']['pin-sha256']) && 1 === \count($options['peer_fingerprint'])) {
                throw new TransportException(__CLASS__.' cannot verify "pin-sha256" fingerprints, please provide a "sha256" one.');
            }

            unset($options['peer_fingerprint']['pin-sha256']);
        }

        $info = [
            'response_headers' => [],
            'url' => $url,
            'error' => null,
            'http_method' => $method,
            'http_code' => 0,
            'redirect_count' => 0,
            'start_time' => 0.0,
            'fopen_time' => 0.0,
            'connect_time' => 0.0,
            'redirect_time' => 0.0,
            'starttransfer_time' => 0.0,
            'total_time' => 0.0,
            'namelookup_time' => 0.0,
            'size_upload' => 0,
            'size_download' => 0,
            'size_body' => \strlen($options['body']),
            'primary_ip' => '',
            'primary_port' => 'http:' === $url['scheme'] ? 80 : 443,
        ];

        if ($onProgress = $options['on_progress']) {
            // Memoize the last progress to ease calling the callback periodically when no network transfer happens
            $lastProgress = [0, 0];
            $onProgress = static function (...$progress) use ($onProgress, &$lastProgress, &$info) {
                $progressInfo = $info;
                $progressInfo['url'] = implode('', $info['url']);
                unset($progressInfo['fopen_time'], $progressInfo['size_body']);

                if ($progress && -1 === $progress[0]) {
                    // Response completed
                    $lastProgress[0] = max($lastProgress);
                } else {
                    $lastProgress = $progress ?: $lastProgress;
                }

                $onProgress($lastProgress[0], $lastProgress[1], $progressInfo);
            };
        }

        // Always register a notification callback to compute live stats about the response
        $notification = static function (int $code, int $severity, ?string $msg, int $msgCode, int $dlNow, int $dlSize) use ($onProgress, &$info) {
            $now = microtime(true);
            $info['total_time'] = $now - $info['start_time'];

            if (STREAM_NOTIFY_PROGRESS === $code) {
                $info['size_upload'] += $dlNow ? 0 : $info['size_body'];
                $info['size_download'] = $dlNow;
            } elseif (STREAM_NOTIFY_CONNECT === $code) {
                $info['connect_time'] += $now - $info['fopen_time'];
            } else {
                return;
            }

            if ($onProgress) {
                $onProgress($dlNow, $dlSize);
            }
        };

        if ($options['resolve']) {
            $this->multi->dnsCache = $options['resolve'] + $this->multi->dnsCache;
        }

        $this->logger && $this->logger->info(sprintf('Request: %s %s', $method, implode('', $url)));

        [$host, $port, $url['authority']] = self::dnsResolve($url, $this->multi, $info, $onProgress);

        if (!isset($options['headers']['host'])) {
            $options['request_headers'][] = 'host: '.$host.$port;
        }

        $context = [
            'http' => [
                'protocol_version' => $options['http_version'] ?: '1.1',
                'method' => $method,
                'content' => $options['body'],
                'ignore_errors' => true,
                'user_agent' => 'Symfony HttpClient/Native',
                'curl_verify_ssl_peer' => $options['verify_peer'],
                'curl_verify_ssl_host' => $options['verify_host'],
                'auto_decode' => false, // Disable dechunk filter, it's incompatible with stream_select()
                'timeout' => $options['timeout'],
                'follow_location' => false, // We follow redirects ourselves - the native logic is too limited
            ],
            'ssl' => array_filter([
                'peer_name' => $host,
                'verify_peer' => $options['verify_peer'],
                'verify_peer_name' => $options['verify_host'],
                'cafile' => $options['cafile'],
                'capath' => $options['capath'],
                'local_cert' => $options['local_cert'],
                'local_pk' => $options['local_pk'],
                'passphrase' => $options['passphrase'],
                'ciphers' => $options['ciphers'],
                'peer_fingerprint' => $options['peer_fingerprint'],
                'capture_peer_cert_chain' => $options['capture_peer_cert_chain'],
                'allow_self_signed' => (bool) $options['peer_fingerprint'],
                'SNI_enabled' => true,
                'disable_compression' => true,
            ], static function ($v) { return null !== $v; }),
            'socket' => [
                'bindto' => $options['bindto'],
                'tcp_nodelay' => true,
            ],
        ];

        $proxy = self::getProxy($options['proxy'], $url);
        $noProxy = $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '';
        $noProxy = $noProxy ? preg_split('/[\s,]+/', $noProxy) : [];

        $resolveRedirect = self::createRedirectResolver($options, $host, $proxy, $noProxy, $info, $onProgress);
        $context = stream_context_create($context, ['notification' => $notification]);
        self::configureHeadersAndProxy($context, $host, $options['request_headers'], $proxy, $noProxy);

        return new NativeResponse($this->multi, $context, implode('', $url), $options, $gzipEnabled, $info, $resolveRedirect, $onProgress, $this->logger);
    }
1285830
public function send(Request $request)
    {
        $response    = new GetResponse();
        $httpRequest = $this->createHttpRequest($request);

        try {
            $httpResponse = $this->client->send($httpRequest);
            $code         = $httpResponse->getStatusCode();
        } catch (RequestException $e) {
            if ($e->getCode() == 404 && $request->notfoundOk) {
                return $response;
            }

            throw $e;
        }

        if ( ! isset($this->validResponseCodes[$code])) {
            throw RiakTransportException::unexpectedStatusCode($code);
        }

        $json    = $httpResponse->json();
        $context = isset($json['context']) ? $json['context'] : null;
        $value   = $json['value'];
        $type    = $json['type'];

        $response->type    = $type;
        $response->context = $context;
        $response->value   = $this->opConverter->fromArray($type, $value);

        return $response;
    }
287343
public function sendRequest(RequestInterface $request): void
    {
        $requestId = $this->getRequestId($request);
        $this->pendingRequests[$requestId] = $this->createPromiseForRequest($request, true);
    }
613072
private function setQueryParameters(TransportRequestInterface $transportRequest, $parameters)
    {
        if(!empty($parameters) && is_array($parameters)) {
            $transportRequest->setQueryParams($parameters);
        }

        return $transportRequest;
    }