Make an HTTP request

@return API results
169333
function http($url, $post_data = null) {/*{{{*/
    $ch = curl_init();
    if (defined("CURL_CA_BUNDLE_PATH")) curl_setopt($ch, CURLOPT_CAINFO, CURL_CA_BUNDLE_PATH);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //////////////////////////////////////////////////
    ///// Set to 1 to verify Server's SSL Cert //////
    //////////////////////////////////////////////////
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    if (isset($post_data)) {
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }

    $response = curl_exec($ch);
    $this->http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $this->last_api_call = $url;
    curl_close ($ch);

	/**
    echo "<pre>";
    echo $url . "\n";
    print_r(explode("&", $post_data)) . "\n";
    print_r($response) . "\n";
    echo "---\n</pre>";
	 */

    return $response;
  }
305333
public function send()
	{
		$mappedParams = $this->map();

		$curler = new \GuzzleHttp\Client(['base_uri' => $this->tgUrl]);

		if (empty($this->multipart)) {
			$response = $curler->request("POST", static::$method, [
				"query" => $mappedParams
			]);
		} else {
			$response = $curler->request("POST", static::$method, [
				"query" => $mappedParams,
				"multipart" => $this->multipart
			]);
		}

		$jsonResponse = json_decode((string)$response->getBody(), true);
		$result = $jsonResponse['result'];
		return static::decodeResult($result);
	}
1209579
public function send(): HttpResponse {
        $ch = $this->createCurl();
        $response = $this->execCurl($ch);
        curl_close($ch);

        return $response;
    }
629956
public function api($apiUrl, $method = 'GET', array $params = [], array $headers = [])
    {
        $client = new HttpClient();
        $response = $client->createRequest()
            ->setMethod($method)
            ->addHeaders($headers)
            ->setUrl($apiUrl)
            ->setData($params)
            ->send();
        return $response->content;
    }
707533
def execute
      request = Net::HTTP::Get.new(@endpoint.path)
      request.add_field('Content-Type', 'application/soap+xml')
      MexResponse.parse(http(@endpoint).request(request).body)
    end
62648
public function send()
  {
    # Set HTTP Response Code
    http_response_code($this->statusCode);

    # Update Cache-Control Header
    if ( empty($this->getHeader('Cache-Control')) ) {
      $this->setHeader('Cache-Control', $this->cacheControl);
    }

    # Set All HTTP headers
    foreach ($this->headers as $header => $value) {
      header($header.': '.$value);
    }

    # Set all cookies
    foreach ($this->cookies as $idx => $cookie) {
      setCookie( $cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly'] );
    }

    # Send Response Body -- if we have something in the $body param
    if ( !empty($this->getBody()) ) {
      echo $this->getBody();
    } else
    if ( !empty($this->getFileBody()) ) {
      readfile($this->getFileBody());
    }

    # Results
    return $this;
  }
771794
protected function createRequest()
    {
        if (!$this->requestPrototype) {
            $request = new HTTP_Request2($this->url);
        } else {
            $request = clone $this->requestPrototype;
            $request->setUrl($this->url);
        }

        foreach (array_keys($this->getProject()->getProperties()) as $propName) {
            if (0 === strpos($propName, 'phing.http.')) {
                $request->setConfig(substr($propName, 11), $this->getProject()->getProperty($propName));
            }
        }

        // set the authentication data
        if (!empty($this->authUser)) {
            $request->setAuth(
                $this->authUser,
                $this->authPassword,
                $this->authScheme
            );
        }

        foreach ($this->configData as $config) {
            $request->setConfig($config->getName(), $config->getValue());
        }

        foreach ($this->headers as $header) {
            $request->setHeader($header->getName(), $header->getValue());
        }

        return $request;
    }
198699
function get($path, $query = null, $headers = null, $curlOpts = null) {
        $payload = $this -> encodePostBody($query);
        
        if ($payload !== "") {
            if (strpos($path, '?')) {
                $url = $path . "&" . $payload;
            } else {
                $url = $path . "?" . $payload;
            }
        }else{
            $url = $path;
        }
        
        return $this -> request($url, self::HTTP_GET, '', $headers, $curlOpts);
    }
1229011
public function send()
    {
        $request = $this->createRequest();

        $response = $this->httpClient->sendRequest($request);

        return $this->mapResponse((array) $this->parseResponse($response));
    }
823803
public function run() {
        // Setup connection
        $resource = curl_init();

        // Set cURL options
        foreach ($this->settings as $option => $setting) {
            curl_setopt($resource, $option, $setting);
        }

        // Process headers
        $headers = [];
        foreach ($this->headers as $key => $value) {
            if (!empty($value)) {
                $headers[] = implode(' : ', [$key, $value]);
            }
            else {
                $this->headers[] = $key;
            }
        }

        // Add the headers
        curl_setopt($resource, CURLOPT_HTTPHEADER, $headers);

        // Execute cURL
        $response = curl_exec($resource);

        // Get the size of the header
        $header_size = curl_getinfo($resource, CURLINFO_HEADER_SIZE);

        // Get the header from the result
        $headers = substr($response, 0, $header_size);

        // Get the body from the result
        $body = substr($response, $header_size);

        // Get the HTTP response code from the result
        $responseCode = curl_getinfo($resource, CURLINFO_HTTP_CODE);

        // Close the connection
        curl_close($resource);

        // Create Result instance
        $this->result = new Result($body, $responseCode, $headers);

        return $this->result;
    }
951543
protected function handleGET()
    {
        $resources = $this->getResources();
        if (is_array($resources)) {
            $includeAccess = $this->request->getParameterAsBool(ApiOptions::INCLUDE_ACCESS);
            $asList = $this->request->getParameterAsBool(ApiOptions::AS_LIST);
            $idField = $this->request->getParameter(ApiOptions::ID_FIELD, static::getResourceIdentifier());
            $fields = $this->request->getParameter(ApiOptions::FIELDS);
            if (!$asList && $includeAccess) {
                foreach ($resources as &$resource) {
                    if (is_array($resource)) {
                        $name = array_get($resource, $idField);
                        $resource['access'] =
                            VerbsMask::maskToArray($this->getPermissions($name));
                    }
                }
            }

            return ResourcesWrapper::cleanResources($resources, $asList, $idField, $fields);
        }

        return $resources;
    }
519438
public final function request()
    {
        if ($this->request == null){
            $this->request = $this->phpContext->createRequest();
        }

        return $this->request;
    }
550070
protected function sendRequest()
    {
        $context = stream_context_create($this->request);
        $response = trim(file_get_contents($this->endpoint, FALSE, $context));
        $this->response = new Response($http_response_header, $response, $this->request);

        return $this->response;
    }
249152
public function do_request($request)
    {
        $http = [];

        $http['method'] = $request->method;

        $headers = [];
        foreach ($request->headers as $k => $v) {
            $headers[] = is_string($k) ? "$k: $v" : $v;
        }

        if (isset($request->options['proxy'])) {
            $parts = parse_url($request->options['proxy']);
            if ($parts['scheme'] !== 'http') {
                throw new NotSupportedException(['only support http type proxy: `:proxy`', 'proxy' => $request->options['proxy']]);
            }

            if (isset($parts['pass'])) {
                $headers[] = 'Proxy-Authorization: Basic ' . base64_encode($parts['user'] . ':' . $parts['pass']);
            }
            $http['proxy'] = 'tcp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : '80');
        }

        $http['header'] = $headers;

        if (is_string($request->body)) {
            $http['content'] = $request->body;
        } elseif (is_array($request->body)) {
            if (isset($options['Content-Type']) && strpos($request->headers['Content-Type'], 'json') !== false) {
                $http['content'] = json_encode($request->body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            } else {
                $http['content'] = http_build_query($request->body);
            }
        }

        $http['timeout'] = $request->options['timeout'];
        $http['ignore_errors'] = true;

        $ssl = [];
        $ssl['verify_peer'] = $request->options['verify_peer'];
        if (isset($request->options['allow_self_signed'])) {
            $ssl['allow_self_signed'] = $request->options['allow_self_signed'];
        } else {
            $ssl['allow_self_signed'] = !$request->options['verify_peer'];
        }

        if (isset($request->options['cafile'])) {
            $ssl['cafile'] = $this->alias->resolve($request->options['cafile']);
        }

        $start_time = microtime(true);

        if (!$stream = @fopen($request->url, 'rb', false, stream_context_create(['http' => $http, 'ssl' => $ssl]))) {
            throw new ConnectionException(['`:url`: `:last_error_message`', 'url' => $request->url]);
        }
        $meta = stream_get_meta_data($stream);
        $body = stream_get_contents($stream);
        fclose($stream);

        $process_time = round(microtime(true) - $start_time, 3);

        $headers = $meta['wrapper_data'];

        for ($i = count($headers) - 1; $i >= 0; $i--) {
            $header = $headers[$i];
            /** @noinspection NotOptimalIfConditionsInspection */
            if (strpos($header, ':') === false && $headers !== '') {
                break;
            }
        }

        if ($i !== 0) {
            $headers = array_slice($headers, $i);
        }

        $content_type = null;
        foreach ($headers as $header) {
            if (strpos($header, 'Content-Type:') === 0) {
                $content_type = trim(substr($header, 13));
                break;
            }
        }

        $http_code = null;
        if ($headers && preg_match('#\d{3}#', $headers[0], $match)) {
            $http_code = (int)$match[0];
        }

        $response = new Response();
        $response->url = $request->url;
        $response->remote_ip = null;
        $response->http_code = $http_code;
        $response->headers = $headers;
        $response->process_time = 0;
        $response->content_type = $content_type;
        $response->body = $body;
        $response->process_time = $process_time;

        return $response;
    }
833410
public function createRequest() {
        $request = new \Amp\Artax\Request();
        $url = null;
        $request->setMethod('');


        $jsonParams = [];
        $value = $this->getFilteredParameter('scopes');
        $jsonParams['scopes'] = $value;
        $value = $this->getFilteredParameter('add_scopes');
        $jsonParams['add_scopes'] = $value;
        $value = $this->getFilteredParameter('remove_scopes');
        $jsonParams['remove_scopes'] = $value;
        $value = $this->getFilteredParameter('note');
        $jsonParams['note'] = $value;
        $value = $this->getFilteredParameter('note_url');
        $jsonParams['note_url'] = $value;
        $value = $this->getFilteredParameter('fingerprint');
        $jsonParams['fingerprint'] = $value;

        //Parameters are parsed and set, lets prepare the request
        if (count($jsonParams)) {
            $jsonBody = json_encode($jsonParams);
            $request->setHeader("Content-Type", "application/json");
            $request->setBody($jsonBody);
        }
        if ($url == null) {
            $url = "https://api.github.com/authorizations/{id}";
        }
        $request->setUri($url);

        return $request;
    }
560846
public function send() {
        $curlUrl = $this->url;
        if ($this->params) {
            $queryString = http_build_query($this->params);
            $separator = parse_url($curlUrl, PHP_URL_QUERY) ? '&' : '?';
            $curlUrl .= $separator . $queryString;
        }

        // Mock the request if self::$mock exists
        if (self::$mock) {
            if (self::$mock['url'] == $curlUrl && self::$mock['method'] == $this->method) {
                return self::$mock['response'];
            }
            return null;
        }

        // Open and configure curl connection
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $curlUrl);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        $headers = array(
            'User-Agent: SiftScience/v' . $this->version . ' sift-php/' . Sift::VERSION
        );
        if ($this->auth) {
            curl_setopt($ch, CURLOPT_USERPWD, $this->auth);
        }

        // HTTP-method-specific configuration.
        if ($this->method == self::POST) {
            if (function_exists('json_encode')) {
                $jsonString = json_encode($this->body);
            } else {
                require_once(dirname(__FILE__) . '/Services_JSON-1.0.3/JSON.php');
                $json = new Services_JSON();
                $jsonString = $json->encodeUnsafe($this->body);
            }

            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
            array_push($headers, 'Content-Type: application/json',
                'Content-Length: ' . strlen($jsonString)
            );

        } else if ($this->method == self::DELETE) {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        }

        foreach ($this->curl_opts as $option => $value) {
            if ($option !== CURLOPT_HTTPHEADER) {
                curl_setopt($ch, $option, $value);
            } else {
                $headers = array_merge($headers, $value);
            }
        }

        // Send the request using curl and parse result
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErrno = curl_errno($ch);
        $curlError = curl_error($ch);
        curl_close($ch);

        return new SiftResponse($result, $httpStatusCode, $this, $curlErrno, $curlError);
    }
546531
private function httpIO()
    {
        $services = [
            'Http\Message\ServerRequest' => 'serverRequest',
            'Http\Input'                 => 'input',
            'Http\Output'                => 'output',
        ];

        foreach ($services as $className => $classOffset) {
            $this->services->load($className, $classOffset);
        }
    }