Send a http request with file_file_get_contents.

@param string      $method
@param array       $headers (optional)
@param null|string $content
@param string      $protocolVersion (default: '1.1')

@return Response
346940
public function send($method, array $headers = [], $content = null, $protocolVersion = '1.1')
    {

        $headers = $this->addCredentials($headers);

        $this->callBeforeListeners('send', [$this->url, $method, &$headers]);

        // We have to recreate the stream every time
        $this->close();

        $header = implode("\r\n", $headers);
        $stream = $this->createHttpStream($method, $header, $content, $protocolVersion);

        $this->stream = $stream;

        // Currently only stream-less connections are supported
        $raw = $stream->toString();

        list($responseHeader, $content) = $this->parseMessage($raw);

        $response = new Response($responseHeader, $content);
        $response->setRaw($raw);

        $this->callAfterListeners('send', [$this->url, $method, &$headers, $response]);

        $this->close();

        return $response;

    }
700143
public function message($protocolVersion, $headers, $body)
    {
        return new Messages\Message\Implementation(
            $protocolVersion,
            $headers,
            $body
        );
    }
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);
        }
    }
513262
function request($method, $body = NULL, $header = array()){
        foreach($body as $key => $val) {
            if($val === null) {
                unset($body[$key]);
            }
        }

        ShortPixel::log("REQUEST BODY: " . json_encode($body));

        $retUrls = array("body" => array(), "headers" => array(), "fileMappings" => array());
        $retPend = array("body" => array(), "headers" => array(), "fileMappings" => array());
        $retFiles = array("body" => array(), "headers" => array(), "fileMappings" => array());

        if(isset($body["urllist"])) {
            $retUrls = $this->requestInternal($method, $body, $header);
        }
        if(isset($body["pendingURLs"])) {
            unset($body["urllist"]);
            //some files might have already been processed as relaunches in the given max time
            foreach($retUrls["body"] as $url) {
                //first remove it from the files list as the file was uploaded properly
                if($url->Status->Code != -102 && $url->Status->Code != -106) {
                    $notExpired[] = $url;
                    if(!isset($body["pendingURLs"][$url->OriginalURL])) {
                        $lala = "cucu";
                    } else
                    $unsetPath = $body["pendingURLs"][$url->OriginalURL];
                    if(isset($body["files"]) && ($key = array_search($unsetPath, $body["files"])) !== false) {
                        unset($body["files"][$key]);
                    }
                }
                //now from the pendingURLs if we already have an answer with urllist
                if(isset($body["pendingURLs"][$url->OriginalURL])) {
                    $retUrls["fileMappings"][$url->OriginalURL] = $body["pendingURLs"][$url->OriginalURL];
                    unset($body["pendingURLs"][$url->OriginalURL]);
                }
            }
            if(count($body["pendingURLs"])) {
                $retPend = $this->requestInternal($method, $body, $header);
                if(isset($retPend['body']->Status->Code) && $retPend['body']->Status->Code < 0) { //something's wrong (API key?)
                    throw new ClientException($retPend['body']->Status->Message, $retPend['body']->Status->Code);

                }
                if(isset($body["files"])) {
                    $notExpired = array();
                    foreach($retPend['body'] as $detail) {
                        if($detail->Status->Code != -102) { // -102 is expired, means we need to resend the image through post
                            $notExpired[] = $detail;
                            $unsetPath = $body["pendingURLs"][$detail->OriginalURL];
                            if(($key = array_search($unsetPath, $body["files"])) !== false) {
                                unset($body["files"][$key]);
                            }
                        }
                    }
                    $retPend['body'] = $notExpired;
                }
            }
        }
        if (isset($body["files"]) && count($body["files"]) ||
            isset($body["buffers"]) && count($body["buffers"])) {
            unset($body["pendingURLs"]);
            $retFiles = $this->requestInternal($method, $body, $header);
        }

        if(!isset($retUrls["body"]->Status) && !isset($retPend["body"]->Status) && !isset($retFiles["body"]->Status)
           && (!is_array($retUrls["body"]) || !is_array($retPend["body"]) || !is_array($retFiles["body"]))) {
            throw new Exception("Request inconsistent status. Please contact support.");
        }

        $body = isset($retUrls["body"]->Status)
            ? $retUrls["body"]
            : (isset($retPend["body"]->Status)
                ? $retPend["body"]
                : (isset($retFiles["body"]->Status)
                    ? $retFiles["body"] :
                    array_merge($retUrls["body"], $retPend["body"], $retFiles["body"])));

        $theReturn =  (object) array("body"    => $body,
                     "headers" => array_unique(array_merge($retUrls["headers"], $retPend["headers"], $retFiles["headers"])),
                     "fileMappings" => array_merge($retUrls["fileMappings"], $retPend["fileMappings"], $retFiles["fileMappings"]));
        ShortPixel::log("REQUEST RETURNS: " . json_encode($theReturn));
        return $theReturn;
    }
149281
public function createSealedRequest(
        string $method,
        string $uri,
        string $body,
        SealingPublicKey $key,
        array $headers = []
    ): RequestInterface {
        $sealed = Simple::seal(
            $body,
            $key
        );
        return new Request(
            $method,
            $uri,
            $headers,
            Base64UrlSafe::encode($sealed)
        );
    }
746895
private function buildRequest($method, $path, $body = null, $contentType = null)
    {
        // copy default headers
        $headers = $this->headers;

        // add Content-Type header if provided
        if ($contentType)
            $headers [] = new HeaderField('Content-Type', $contentType);

        $request = new Request(
            $method,
            $this->url->getUrlForRelativePath($path),
            $headers,
            $body
        );

        // pass the request through the filter chain
        foreach ($this->filters as $filter) {
            $request = $filter->request($request);
        }

        return $request;
    }
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;
    }
171743
public function createRequest($method, $url = '', array $headers = [])
    {
        return $this->client->createRequest($method, $url, $headers);
    }
944963
public function request(string $uri, string $method = null, array $query = null, $body = null, array $headers = null):ResponseInterface{
		$method    = \strtoupper($method ?? 'GET');
		$headers   = Psr7\normalize_request_headers($headers);
		$request   = new Request($method, Psr7\merge_query($uri, $query ?? []));

		if(\in_array($method, ['DELETE', 'PATCH', 'POST', 'PUT'], true) && $body !== null){

			if(\is_array($body) || \is_object($body)){

				if(!isset($headers['Content-type'])){
					$headers['Content-type'] = 'application/x-www-form-urlencoded';
				}

				if($headers['Content-type'] === 'application/x-www-form-urlencoded'){
					$body = \http_build_query($body, '', '&', \PHP_QUERY_RFC1738);
				}
				elseif($headers['Content-type'] === 'application/json'){
					$body = \json_encode($body);
				}
				else{
					$body = null; // @todo
				}

			}

			$request = $request->withBody(Psr17\create_stream((string)$body));
		}

		foreach($headers as $header => $value){
			$request = $request->withAddedHeader($header, $value);
		}

		return $this->sendRequest($request);
	}
117473
private function processMethod($method, array $options, array $headers, array $body = [])
    {
        if ($method === 'get') {
            if ($body !== []) {
                throw new \Exception('Issuing a GET request with a body');
            }
            $options[CURLOPT_HTTPGET] = 1;
        } elseif ($method === 'post') {
            $data_string = json_encode($body);

            $options[CURLOPT_POST] = 1;
            $options[CURLOPT_POSTFIELDS] = $data_string;

            array_push($headers, 'Content-Type: application/json');
            array_push($headers, 'Content-Length: ' . strlen($data_string));
        } else {
            throw new \Exception('Unrecognized method ' . strtoupper($method));
        }

        return [$options, $headers];
    }
792168
private function send($method, $url, array $data = [], array $headers = [], $cacheMinutes = 0)
    {
        $method = strtolower($method);

        try
        {
            return $this->courier->$method($url, $data, $headers, $cacheMinutes);
        }
        catch (HttpRequestException $exception)
        {
            $response = $exception->response();

            if ($response->getResponseType() == 'application/json')
            {
                $response = $response->toArray();
                $error = sprintf('Twitter Error: %s (Error %d)', $response['errors'][0]['message'], $response['errors'][0]['code']);
            }
            else
            {
                $error = sprintf('HTTP Error: %s (Error %d)', $exception->getMessage(), $exception->getCode());
            }

            throw new TwitterException($error);
        }
    }
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'],
    ];
  }
336355
private function _buildRequest($method, $path, $body = null, $contentType = null)
	{
		// copy default headers
		$headers = $this->_headers;

		// add Content-Type header if provided
		if ($contentType)
			$headers []= new HeaderField('Content-Type', $contentType);

		$request = new Request(
			$method,
			$this->_url->getUrlForRelativePath($path),
			$headers,
			$body
		);

		// pass the request through the filter chain
		foreach($this->_filters as $filter)
		{
			$request = $filter->request($request);
		}

		return $request;
	}
909282
public function request($method = self::REQUEST_POST, $resource, array $params = [], array $headers = [])
    {
        $signature = $this->createSignature($resource);
        $method = strtoupper($method);

        $options = [
            'headers' => array_merge($headers, [
                'X-Auth-Key' => $this->key,
                'X-Auth-Workspace' => $this->workspace,
                'X-Auth-Signature' => $signature,
                'Content-Type' => 'application/json; charset=utf-8',
                'Accept' => 'application/json'
            ])
        ];

        /**
         * If POST and data is not an url then send data in body as json string
         */
        if ($method === self::REQUEST_POST && isset($params['data']) && !self::isUrl($params['data']))
        {
            if (is_string($params['data']))
            {
                $params['data'] = self::stringToArray($params['data']);
            }

            if ($params['data'])
            {
                $options[\GuzzleHttp\RequestOptions::JSON] = $params['data'];
                unset($params['data']);
            }
        }

        $options[\GuzzleHttp\RequestOptions::QUERY] = $params;
        return $this->handleRequest($method, $resource, $options);
    }
1061742
private function procPacket($method, $url, $data = null, $headers = array()) {
    /*
     * For now we only data data as strings. Streams and other formats will be
     * permitted later.
     */
    if($data && !is_string($data)) {
      throw new SagException('Unexpected data format. Please report this bug.');
    }

    if($this->pathPrefix && is_string($this->pathPrefix)) {
      $url = $this->pathPrefix . $url;
    }

    // Filter the use of the Expect header since we don't support Continue headers.
    $headers['Expect'] = isset($headers['Expect']) ? $headers['Expect'] : null;
    if(!$headers['Expect']){
        /*
       * PHP cURL will set the Expect header to 100-continue if we don't set it
       * ourselves. See https://github.com/sbisbee/sag/pull/51
       */
        $headers['Expect'] = (isset($headers['expect']) && $headers['expect']) ? $headers['expect'] : ' '; //1 char string, so it's == to true
    }

    if(strtolower($headers['Expect']) === '100-continue') {
      throw new SagException('Sag does not support HTTP/1.1\'s Continue.');
    }

    // Build the request packet.
    $headers["Host"] = "{$this->host}:{$this->port}";
    $headers["User-Agent"] = "Sag/%VERSION%";

    /*
     * This prevents some unRESTful requests, such as inline attachments in
     * CouchDB 1.1.0, from sending multipart responses that would break our
     * parser.
     */
    $headers['Accept'] = 'application/json';

    //usernames and passwords can be blank
    if($this->authType == Sag::$AUTH_BASIC && (isset($this->user) || isset($this->pass))) {
      $headers["Authorization"] = 'Basic '.base64_encode("{$this->user}:{$this->pass}");
    }
    elseif($this->authType == Sag::$AUTH_COOKIE && isset($this->authSession)) {
      $headers['Cookie'] = array( 'AuthSession' => $this->authSession );
      $headers['X-CouchDB-WWW-Authenticate'] = 'Cookie';
    }

    if(is_array($this->globalCookies) && sizeof($this->globalCookies)) {
      //might have been set before by auth handling
      if($headers['Cookie']) {
        $headers['Cookie'] = array_merge($headers['Cookie'], $this->globalCookies);
      }
      else {
        $headers['Cookie'] = $this->globalCookies;
      }
    }

    /*
     * Checking this again because $headers['Cookie'] could be set in two
     * different logic paths above.
     */
    if(!empty($headers['Cookie'])) {
      $buff = '';

      foreach($headers['Cookie'] as $k => $v) {
        $buff = (($buff) ? ' ' : '') . "$k=$v;";
      }

      $headers['Cookie'] = $buff;
      unset($buff);
    }

    /*
     * JSON is our default and most used Content-Type, but others need to be
     * specified to allow attachments.
     */
    if(!isset($headers['Content-Type'])) {
      $headers['Content-Type'] = 'application/json';
    }

    if($data) {
      $headers['Content-Length'] = strlen($data);
    }

    return $this->httpAdapter->procPacket($method, $url, $data, $headers);
  }
116004
public function request(string $method, string $url, array $headers = [], string $body = ''): ResponseInterface
    {
        $request = Factory::request($method, $url, $headers, $body);

        return $this->sendRequest($request);
    }
951297
public function call($method = 'GET', $uri = null, $headers = null, $body = null, array $options = array(), $classToUnserialize = null)
    {
        $request = $this->client->createRequest($method, $uri, $headers, $body, $options);

        if ($classToUnserialize) {
            return $this->serializer->deserialize(
                (string) $this->send($request)->getBody(),
                $classToUnserialize,
                'xml'
            );
        }

        return $this->send($request);
    }