Sends an HTTP request to the CouchDB server.

@param string $method
@param string $url
@param string $payload

@return array

@throws RuntimeException
765779
public function send($method, $url, $payload = null)
    {
        $socket = @fsockopen($this->host, $this->port, $errno, $errstr);

        if (!$socket) {
            throw new RuntimeException($errno.': '.$errstr);
        }

        $request = sprintf(
          "%s %s HTTP/1.1\r\nHost: %s:%d\r\nContent-Type: application/json\r\nConnection: close\r\n",
          $method,
          $url,
          $this->host,
          $this->port
        );

        if ($payload !== null) {
            $request .= 'Content-Length: '.strlen($payload)."\r\n\r\n".
                        $payload;
        }

        $request .= "\r\n";

        // @codeCoverageIgnoreStart
        if ($this->debug) {
            echo $request;
        }
        // @codeCoverageIgnoreEnd

        fwrite($socket, $request);

        $buffer = '';

        while (!feof($socket)) {
            $buffer .= fgets($socket);
        }

        list($headers, $body) = explode("\r\n\r\n", $buffer);

        return ['headers' => $headers, 'body' => $body];
    }
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;
    }
475623
public function request($method, $url, $params = array())
    {
        if (mb_substr($url, 0, 1, 'UTF-8') === '/') {
            $url = $this->api_endpoint . $url;
        }

        $remote_addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
        $session_id  = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
        $user_agent  = sprintf("%s/%s PHP/%s %s",
            self::USER_AGENT,
            self::VERSION,
            phpversion(),
            $this->platform
        );

        $headers = [
            'Accept: application/json',
            'Session-Id: ' . $session_id,
            'Forwarded: ' . $remote_addr,
            'Authorization:  Bearer ' . $this->merchant_token,
            'Content-Type: application/json'
        ];

        curl_setopt_array($this->curl, [
            CURLOPT_USERAGENT     => $user_agent,
            CURLOPT_HTTPHEADER    => $headers,
            CURLOPT_URL           => $url,
            CURLOPT_CUSTOMREQUEST => $method
        ]);

        if (count($params) > 0) {
            $data      = json_encode($params, JSON_PRETTY_PRINT);
            $headers[] = 'Content-Length: ' . strlen($data);

            curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
        }

        $body = curl_exec($this->curl);
        $info = curl_getinfo($this->curl);
        $code = (int)($info['http_code'] / 100);
        switch ($code) {
            case 0:
                $error = curl_error($this->curl);
                $errno = curl_errno($this->curl);
                throw new Exception(sprintf('Error: %s. Code: %s.', $error, $errno));
            case 1:
                throw new Exception(sprintf('Invalid HTTP Code: %s', $info['http_code']));
            case 2:
            case 3:
                return new Response($body);
            case 4:
            case 5:
                throw new Exception(sprintf('API Error: %s. HTTP Code: %s', $body, $info['http_code']));
            default:
                throw new Exception(sprintf('Invalid HTTP Code: %s', $info['http_code']));
        }
    }
1018549
private function createRequest($method, array $payload)
    {
        $request = new Request(
            'POST',
            self::API_BASE_URL . $method,
            ['Content-Type' => 'application/x-www-form-urlencoded'],
            http_build_query($payload)
        );

        return $request;
    }
258082
public function iSendARequestWithBody($method, $url, PyStringNode $body)
    {
        $this->restApiBrowser->sendRequest($method, $url, (string) $body);
    }
651164
protected function sendJsonTransaction(array $parameters, $url = null, $method = 'POST', array $headers = ['Accept: application/vnd.pagseguro.com.br.v3+json;charset=ISO-8859-1', 'Content-Type: application/json; charset=UTF-8'])
    {
        if ($url === null) {
            $url = $this->url['transactions'];
        }
        $url .= '?email='.$this->email.'&token='.$this->token;

        $parameters = $this->array_filter_recursive($parameters);

        array_walk_recursive($parameters, function (&$value, $key) {
            $value = utf8_encode($value);
        });
        $parameters = json_encode($parameters);

        if ($method == 'GET') {
            $parameters = null;
        }

        $result = $this->executeCurl($parameters, $url, $headers, $method);

        return $this->formatResultJson($result);
    }
624470
protected function query($uri, array $params = [], $method = self::METHOD_POST)
    {
        $request = new Request($method, $uri, [
            'Content-Type'  => 'application/json',
            'Authorization' => 'Token ' . $this->token,
            'X-Secret'      => $this->secret,
        ], 0 < count($params) ? json_encode($params) : null);

        $response = $this->httpClient->send($request, $this->httpOptions);

        $result = json_decode($response->getBody(), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException('Error parsing response: ' . json_last_error_msg());
        }

        if (empty($result)) {
            throw new RuntimeException('Empty result');
        }

        return array_shift($result);
    }
79810
public function send($method, $uri, $body = null, array $query = [], array $headers = [], array $options = [])
    {
        $this->validateMethod($method);

        $query = array_merge($this->getDefaultQuery(), $query);
        $headers = array_merge($this->getDefaultHeaders(), $headers);

        $this->lastResponse = $this->client->send($method, $uri, $body, $query, $headers, $options);

        $this->validateResponse($this->lastResponse);

        return $this->lastResponse;
    }
63989
protected function payloadExec($method, $args = []) {
        $this->getPayloadInstance();
        if (method_exists($this->instance, $method)) {
            return $this->di->call([$this->instance, $method], $args);
        }
        return null;
    }
645168
public function post(string $url, ?array $payload = null): TransportClientResponse {
        return $this->sendRequest($url, array(
            CURLOPT_POST       => 1,
            CURLOPT_POSTFIELDS => $payload
        ));
    }
980673
public static function sendRequest($method = 'sendMessage', $params)
    {
        $curl = curl_init(self::$api_url . self::$api_token . '/'. $method);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        if(self::$proxy) {
            curl_setopt_array($curl, self::setProxy());
        }

        $curl_result = curl_exec($curl);
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if ($http_code != 200) {
            if ($curl_result) {
                $curl_result = json_decode($curl_result, true);
                throw new \Exception($curl_result['description']);
            }
            throw new \Exception('an error was encountered');
        }

        return $curl_result;
    }
1364722
private function request($method, $uri, $body = array())
    {
        try {
            $res = $this->client->request($method, $uri, $body);
            return json_decode($res->getBody());
        } catch(RequestException $e){
            $res = VariableUtil::json2Array(
                json_decode($e->getResponse()->getBody()->getContents())[0]
            );
            /*
             * If the session expired, then we must request a new token with the
             * refresh token.
             */
            if(isset($res['errorCode']) && $res['errorCode'] == 'INVALID_SESSION_ID'){
                $this->refreshToken($method, $uri, $body);
            } else {
                throw new ExternalApiException($e->getMessage(), $e->getCode(), $e);
            }
        }
    }
901466
protected function _sendRawRequest($url, $method = Request::METHOD_GET, $body = '', \Closure $initializeRequest = null)
    {
        $logSeverity = SolrLogManager::INFO;
        $exception = null;

        try {
            $request = $this->buildSolariumRequestFromUrl($url, $method);

            if($initializeRequest !== null) {
                $request = $initializeRequest($request);
            }

            $response = $this->executeRequest($request);
        } catch (HttpException $exception) {
            $logSeverity = SolrLogManager::ERROR;
            $response = new ResponseAdapter($exception->getBody(), $exception->getCode(), $exception->getMessage());
        }

        if ($this->configuration->getLoggingQueryRawPost() || $response->getHttpStatus() != 200) {
            $message = 'Querying Solr using '.$method;
            $this->writeLog($logSeverity, $message, $url, $response, $exception, $body);
        }

        return $response;
    }
804247
protected function sendRequest($method, $url, $data = [], $headers = [])
    {
        $this->addRequestSourceHeader($headers);
        $data['http_errors'] = false;
        $data['headers'] = $headers;
        $response = $this->http_client->request($method, $url, $data);

        return $response;
    }
694433
protected function request($url, $method = 'GET', array $params = array())
    {
        $this->client->setEventDispatcher($this->getEventDispatcher());
        $this->client->activatePlugins($this->registerPlugins);

        $response = $this->client->request($method, $url, $params);
        return $response;
    }
133843
protected function query($method, $url, array $parameters = null)
    {
        return $this->httpClient->query($method, $url, $parameters);
    }
183319
private function makeRequest($method, $uri, array $parameters = []) {
    try {
      $response = $this->request($method, $uri, $parameters);
      
      if (200 != $response->getStatusCode()) {
        throw new ActivenetClientException(sprintf('Got non 200 response code for the uri %s.', $uri));
      }

      if (!$body = $response->getBody()) {
        throw new ActivenetClientException(sprintf('Failed to get response body for the uri %s.', $uri));
      }

      if (!$contents = $body->getContents()) {
        throw new ActivenetClientException(sprintf('Failed to get body contents for the uri: %s.', $uri));
      }

      $object = json_decode($contents);

      // Check if object contains data.
      if (isset($object->body)) {
        return $object->body;
      }

      throw new ActivenetClientException(sprintf('Got unknown body name for method %s.', $method));
    }
    catch (\Exception $e) {
      throw new ActivenetClientException(sprintf('Failed to make a request for uri %s with message %s.', $uri, $e->getMessage()));
    }

  }