/** * @param array $config */ public function __construct($config = array()) { $this->config = array_merge(array('base_uri' => null, 'username' => null, 'password' => null, 'mime' => null, 'timeout' => null), (array) $config); $this->base_uri = $this->config['base_uri']; $template = Request::init()->mime($this->config['mime']); if ($this->config['username']) { $template->authenticateWith($this->config['username'], $this->config['password']); } Request::ini($template); }
/** * Construt a Request * * @param Auth $auth SkyHub Auth information to send on headers */ public function __construct(Auth $auth) { $this->auth = $auth; $this->jsonHandler = new \SkyHub\Handlers\JsonHandler(); $this->jsonHandler->init(array()); Httpful::register(\Httpful\Mime::JSON, $this->jsonHandler); // creates a request template, every request must have the auth headers $this->requestTemplate = HttpfulRequest::init()->expectsJson()->addHeader('X-User-Email', $this->auth->getEmail())->addHeader('X-User-Token', $this->auth->getToken()); HttpfulRequest::ini($this->requestTemplate); }
public function navigate($link, $data = null, $queryParams = null) { $url = $this->url . $link->Uri; $request = \Httpful\Request::init()->addHeader("Authorization", $this->getAuthorizationToken())->method($link->Method)->uri($url)->addHeader("Accept", $link->Type)->contentType(findMimeTypeUsingUrl($url)); if (($link->Method === "POST" || $link->Method === "PUT") && $data !== null) { if (property_exists($link, 'VersionNumber')) { $request->addHeader($this->ifNoneMatch, $link->VersionNumber); } $request->body(json_encode($data)); } $response = $request->send(); $result = null; if ($response->hasErrors()) { $result = $response->body; throw new \NFleetException($result); } else { if ($link->Method === "GET") { $result = $response->body; if (isset($response->headers['etag'])) { $result->VersionNumber = $response->headers['etag']; } } elseif ($link->Method === "POST" || $link->Method === "PUT") { $result = $this->createResponseData($response->headers['location'], $response->headers['Content-Type']); } } return $result; }
/** * @param $route * @param $type * @param $data * @return array * @throws AcendaException * @throws Httpful\Exception\ConnectionErrorException */ public function performRequest($route, $type, $data) { $httpful = Httpful\Request::init(); if (!$this->bypass_ssl) { $httpful = $httpful->withStrictSSL(); } $data_json = is_array($data) ? json_encode($data) : $data; $url = $this->store_url . (!empty($this->token['access_token']) ? "/api" . $route . "?access_token=" . $this->token['access_token'] : $route); switch (strtoupper($type)) { case 'GET': //Append the query. $url .= "&query=" . $data_json; $response = $httpful->get($url)->send(); break; case 'PUT': $response = $httpful->put($url, $data_json)->sendsJson()->send(); break; case 'POST': $response = $httpful->post($url, $data_json)->sendsJson()->send(); break; default: throw new AcendaException('Verb ' . $type . ' Not Understood'); } //Default in this switch is failure. All failures should fall through to default. switch ($response->code) { case 200: case 201: return $this->requestSuccess($response); default: return $this->requestFailure($response); } }
/** * Prepare request template with default values. All those can be simply * changed by calling appropriate methods on the request, which will override * the template set here. Here we set Basic Auth and Accept header to be * used in all requests. * */ protected function prepareRequestTemplate() { // Create the Request template. static::$requestTemplate = Request::init()->method(Http::GET)->basicAuth(static::$settings->isvuUsername, static::$settings->isvuPassword)->addHeader('Accept', static::$settings->defaultAcceptHeader); // Set it as a template. Request::ini(static::$requestTemplate); }
/** * Post Request * * @param string $uri * @return \Httpful\Response */ public function post($uri, $params = array()) { if ($params) { $uri .= "?" . http_build_query($params); } $this->output("POST : " . $uri); return new \Httpful\Response("", "HTTP/1.1 200 OK\r\n", \Httpful\Request::init()); }
/** * GitHubRestClient constructor. * @param $request Request */ public function __construct($request = null) { if (null != $request) { $this->request = $request; } else { $this->request = Request::init(); } }
/** * @param $client_id Developer ID, usually in form of user@domain.com * @param $client_secret Developer key provided by Acenda. * @param $store_url The URL of the store we are working with. * @param $plugin_name Friendly name for localeconv(oid)gs etc. I don't think this is implemented. * @param $bypass_ssl Rather the SSL verification should be strict or not. * @throws AcendaException */ public function __construct($client_id, $client_secret, $store_name, $bypass_ssl = false) { $this->httpful = Httpful\Request::init(); if (!$bypass_ssl) { $this->httpful = $this->httpful->withStrictSSL(); } Authentication::init($client_id, $client_secret, $this->httpful); $this->generateStoreUrl($store_name); }
/** * Make a JSON request * * @param string $method GET, POST, PUT, DELETE, etc. * @param array $segments for example array('account', 'all') * @param array $data the post / put data */ public static function request($method, $segments, $data = array()) { $url = implode('', static::url($segments, $data)); $config = static::config(); $response = Request::init($method)->uri($url)->mime('json')->basicAuth($config['username'], $config['password'])->send(); if ($response->code === 404) { throw new Exception('API method "' . $url . '" does not exist.'); } if ($response->code === 401) { throw new Exception('Unauthorized to use this API method "' . $url . '".'); } return new Response($response->code, $response->body); }
public function testListUserRepositories() { $this->mockRequest->expects($this->once())->method('expectsJson')->willReturn($this->mockRequest); $this->mockRequest->expects($this->once())->method('uri')->with($this->equalTo('https://api.github.com/users/jgiovaresco/repos'))->willReturn($this->mockRequest); $this->mockRequest->expects($this->once())->method('send')->willReturn(new \Httpful\Response('[{ "id": 123, "name": ".vim" },{ "id": 124, "name": "repocount" }]', "HTTP/1.1 200 OK\n\t\t\t\t\tContent-Type: application/json\n\t\t\t\t\tConnection: keep-alive\n\t\t\t\t\tTransfer-Encoding: chunked\r\n", $req = \Httpful\Request::init()->sendsAndExpects(\Httpful\Mime::JSON))); $repositories = $this->gitHubRestClient->listUserRepositories(Employee::builder()->withId('123')->withUsername('jgiovaresco')->build()); expect($repositories)->to->have->length(2); expect($repositories[0]->name())->to->equal('.vim'); expect($repositories[1]->name())->to->equal('repocount'); }
/** * Call LendingClub and gather all loans * * @return callable * @throws \Httpful\Exception\ConnectionErrorException */ public function callback() { $uri = 'https://api.lendingclub.com/api/investor/1/loans/listing'; /** @var \PhpAmqpLib\Message\AMQPMessage $args */ return function ($args) use($uri) { $request = Request::init('GET'); $auth_key = json_decode($args->body)[0]; $request->uri($uri); $request->addHeader('Accept', 'application/json'); $request->addHeader('Content-Type', 'application/json'); $request->addHeader('Authorization', $auth_key); /** @var \Httpful\Response $response */ $response = $request->send(); echo $response->code . PHP_EOL; // Perform DB operation with response }; }
/** * send off the request to Shopify, encoding the data as JSON * * @param string $method * @param string $page * @param array $data * * @return array */ public function makeRequest($method, $page, $data = []) { $url = $this->url . "/" . $page; if ($method == 'GET' && !empty($data)) { $url .= '?' . http_build_query($data); } $r = Request::init($method)->uri($url); if ($data && $method != 'GET') { $r->body(json_encode($data), 'application/json'); } $r = $r->send(); if ($r->code !== 200) { return ['error' => $r->body, 'url' => $url, 'request' => '', 'status' => $r->code, 'response' => $r->body]; } else { return json_decode(json_encode($r->body), true); } }
public static function makeRequest($method, $uri, $many = false, $payload = array()) { if (empty($method)) { throw new \InvalidArgumentException('method'); } if (empty($uri)) { throw new \InvalidArgumentException('uri'); } $uri = str_replace('{resource}', self::getResourceName(), $uri); $request = \Httpful\Request::init($method)->uri(self::API_URL . $uri)->addHeader('Authorization', "Token " . self::API_KEY)->addHeader('Accept', 'application/json')->sendsJson(); if (!empty($payload)) { if ($method == \Httpful\Http::GET) { $query_str = http_build_query($payload, null, '&'); $query_str = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query_str); $request = $request->uri($request->uri . '?' . $query_str); } else { $request = $request->body($payload); } } $response = $request->send(); if ($response->code >= 500) { throw new \Exception("{$response->code}: Internal server error. Check server logs."); } else { if ($response->code >= 400) { $details = is_object($response->body) ? print_r($response->body, true) : 'Check server logs.'; throw new \Exception("{$response->code}: {$details}", $response->code); } } if ($many) { $resources = array(); foreach ($response->body->results as $json_res) { $resources[] = (array) $json_res; } if (isset($response->body->next)) { $next_url = $response->body->next; if ($next_url) { $next_url = substr($next_url, strlen(self::API_URL)); $resources = array_merge($resources, self::makeRequest($method, $next_url, $many)); } } return $resources; } else { return (array) $response->body; } }
/** * Makes a call to the API. * * This method will make the actial API call by the given arguments. It * will return the response on success (200) or will throw an exception * on failure. * * @param string $method The HTTP method to use (e.g. Http::GET, Http::POST, etc.). * @param string $resourcePath The path to the resource (e.g. contacts/john@example.com/) * @param string $payload The data that is sent to the service. Not used for GET or DELETE. * @return \Httpful\Response The response object from the service. * @throws \Gan\ApiException */ public function call($method, $resourcePath, $payload = null) { $uri = $this->baseUri . $resourcePath; Request::ini($this->requestTemplate); $request = Request::init($method)->uri($uri); if ($payload) { $request->body($payload); } try { $response = $request->send(); } finally { Request::resetIni(); } if (floor($response->code / 100) != 2) { throw new ApiException($response); } return $response; }
/** * Creates an HTTP Request manager with additional header support for Plex. * Endpoint is the URL to request from, with optional proxy parameter. * expectEmptyResponse when set to true does not try and parse the result as XML. * * @param string $endPoint * @param bool|Proxy $proxy */ public function __construct($endPoint, $proxy = false, $expectEmptyResponse = false) { $this->endPoint = $endPoint; $this->template = HttpfulRequest::init(); if ($expectEmptyResponse) { $this->template->withoutAutoParse(); } else { $this->template->expectsXml(); } if ($proxy) { $this->template->useProxy($proxy->host, $proxy->port, $proxy->authType); } foreach ($this->headers as $header => $value) { if ($value) { $this->setHeader($header, $value); } } }
/** * {@inheritdoc} */ protected function doSendInternalRequest(InternalRequestInterface $internalRequest) { $request = Request::init($internalRequest->getMethod())->whenError(function () { })->addOnCurlOption(CURLOPT_HTTP_VERSION, $this->prepareProtocolVersion($internalRequest))->timeout($this->getConfiguration()->getTimeout())->uri($url = (string) $internalRequest->getUrl())->addHeaders($this->prepareHeaders($internalRequest))->body($this->prepareContent($internalRequest)); if (defined('CURLOPT_CONNECTTIMEOUT_MS')) { $request->addOnCurlOption(CURLOPT_CONNECTTIMEOUT_MS, $this->getConfiguration()->getTimeout() * 1000); } else { // @codeCoverageIgnoreStart $request->addOnCurlOption(CURLOPT_CONNECTTIMEOUT, $this->getConfiguration()->getTimeout()); } // @codeCoverageIgnoreEnd if ($internalRequest->hasFiles()) { $request->mime(Mime::UPLOAD); } try { $response = $request->send(); } catch (\Exception $e) { throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage()); } return $this->getConfiguration()->getMessageFactory()->createResponse($response->code, ReasonPhraseExtractor::extract($response->raw_headers), ProtocolVersionExtractor::extract($response->raw_headers), $response->headers->toArray(), BodyNormalizer::normalize($response->body, $internalRequest->getMethod())); }
private function sendRequest($endpoint, $method = Http::GET, $payload = null) { $template = Request::init()->method($method)->sendsType(Mime::JSON); if (isset($this->auth_header)) { $template->addHeader('Authorization', 'Basic ' . $this->auth_header); } Request::ini($template); $r = null; switch ($method) { case Http::GET: $r = Request::get(self::API_HOST . $endpoint . '?' . http_build_query($payload))->send(); break; case Http::POST: $r = Request::post(self::API_HOST . $endpoint)->body(json_encode($payload))->send(); break; default: throw new \Exception("Method not implemented."); break; } if ($r->hasErrors() || isset($r->body->status_code) && $r->body->status_code != 200) { throw new \Exception($r); } return $r; }
/** * @param $url: url of the requested resource * * @param $http_opts: Options for the HTTP request, keys: * - method: request method (GET, PROPFIND, etc.) * - content: request body * - header: array of HTTP request headers as simple strings * * @param $carddav: config array containing at least the keys * - url: base url, used if $url is a relative url * - username * - password: password (encoded/encrypted form as stored in DB) */ public function cdfopen($url, $http_opts, $carddav) { $redirect_limit = 5; $rcmail = rcmail::get_instance(); $username = $carddav['username']; $password = self::decrypt_password($carddav['password']); $baseurl = $carddav['url']; // determine calling function for debug output $caller = self::getCaller(); $local = $rcmail->user->get_username('local'); $domain = $rcmail->user->get_username('domain'); // Substitute Placeholders if ($username == '%u') { $username = $_SESSION['username']; } if ($username == '%l') { $username = $local; } if ($password == '%p') { $password = $rcmail->decrypt($_SESSION['password']); } $baseurl = str_replace("%u", $username, $carddav['url']); $url = str_replace("%u", $username, $url); $baseurl = str_replace("%l", $local, $baseurl); $url = str_replace("%l", $local, $url); $baseurl = str_replace("%d", $domain, $baseurl); $url = str_replace("%d", $domain, $url); // if $url is relative, prepend the base url $url = self::concaturl($baseurl, $url); do { $isRedirect = false; if (self::DEBUG) { $this->debug("{$caller} requesting {$url} [RL {$redirect_limit}]"); } $httpful = \Httpful\Request::init(); $scheme = strtolower($carddav['authentication_scheme']); if ($scheme != "basic" && $scheme != "digest") { /* figure out authentication */ $httpful->addHeader("User-Agent", "RCM CardDAV plugin/1.0.0"); $httpful->uri($url); $httpful->method($http_opts['method']); $error = $httpful->send(); $httpful = \Httpful\Request::init(); $scheme = "unknown"; if (preg_match("/\\bDigest\\b/i", $error->headers["www-authenticate"])) { $httpful->digestAuth($username, $password); $scheme = "digest"; } else { if (preg_match("/\\bBasic\\b/i", $error->headers["www-authenticate"])) { $httpful->basicAuth($username, $password); $scheme = "basic"; } } if ($scheme != "unknown") { carddav_backend::update_addressbook($carddav['abookid'], array("authentication_scheme"), array($scheme)); } } else { if (strtolower($scheme) == "digest") { $httpful->digestAuth($username, $password); } else { if (strtolower($scheme) == "basic") { $httpful->basicAuth($username, $password); } } } $httpful->addHeader("User-Agent", "RCM CardDAV plugin/1.0.0"); $httpful->uri($url); $httpful->method($http_opts['method']); if (array_key_exists('content', $http_opts) && strlen($http_opts['content']) > 0 && $http_opts['method'] != "GET") { $httpful->body($http_opts['content']); } if (array_key_exists('header', $http_opts)) { foreach ($http_opts['header'] as $header) { $h = explode(": ", $header); if (strlen($h[0]) > 0 && strlen($h[1]) > 0) { // Only append headers with key AND value $httpful->addHeader($h[0], $h[1]); } } } $reply = $httpful->send(); $scode = $reply->code; if (self::DEBUG) { $this->debug("Code: {$scode}"); } $isRedirect = $scode > 300 && $scode < 304 || $scode == 307; if ($isRedirect && strlen($reply->headers['location']) > 0) { $url = self::concaturl($baseurl, $reply->headers['location']); } else { $retVal["status"] = $scode; $retVal["headers"] = $reply->headers; $retVal["body"] = $reply->raw_body; if (self::DEBUG_HTTP) { $this->debug_http("success: " . var_export($retVal, true)); } return $retVal; } } while ($redirect_limit-- > 0 && $isRedirect); return $reply->code; }
public function search() { if (!Session::has('api_settings')) { return array('status' => 0); } $api_settings = Session::get('api_settings'); $first_time = $api_settings['current'] == 0; $url = sprintf("https://%s:%s@%s/api/v1/messages/search?q=%s", $api_settings['username'], $api_settings['password'], $api_settings['host'], $api_settings['query_string']); if (!$first_time) { $url .= sprintf("&from=%s&size=100", $api_settings['current']); } $http_template = RequestClient::init()->method('GET')->withoutStrictSsl()->withoutAutoParsing(); RequestClient::ini($http_template); $res = RequestClient::get($url)->send(); if (!$res->hasErrors() && $res->hasBody()) { $data = json_decode($res->body, true); if ($first_time) { $total = intval($data['search']['results']); $api_settings['total'] = $total; } $count = 0; foreach ($data['tweets'] as $tweet) { $flat = $this->array_flat($tweet); Storage::disk('local')->append($api_settings['file_name'], json_encode($flat, JSON_UNESCAPED_UNICODE) . ','); $count++; } $api_settings['current'] += $count; Session::put('api_settings', $api_settings); return array('status' => 1, 'total' => $api_settings['total'], 'current' => $api_settings['current']); } return array('status' => 0); }
public function sendPayload($job, $data) { Event::fire('grohman.tattler.sendPayload', [$data]); $result = HRequest::init()->uri($this->tattlerApi . '/tattler/emit')->sendsType('application/json')->body($data['payload'])->method('POST')->send(); if ($job) { $job->delete(); return; } return $result->hasErrors() == false; }
/** * @param IRequest $request * @return IResponse */ public function sendRequest(IRequest $request) { $response = \Httpful\Request::init()->addHeader('Authorization', 'Bearer ' . Paystack::getApiKey())->uri($request->getUrl())->method($request->getType())->addHeaders($request->getHeaders())->body($request->getBody())->sendsJson()->send(); $iResponse = new Response($response->code, $response->body); return $iResponse; }
/** * Method to set template of request */ private function setTemplate($method) { // Register a new mime type handler if we expect a Json, so the response is decoded as an array. // Extracted from: http://stackoverflow.com/a/22597037 if ($this->mimeType == 'json') { $jsonHandler = new JsonHandler(array('decode_as_array' => true)); Httpful::register('application/json', $jsonHandler); } // Create template $template = Request::init()->method($this->getMethod($method))->expects($this->mimeType)->sendsType(Mime::FORM); // Add custom headers to request if ($this->headers !== null && is_array($this->headers) && !empty($this->headers)) { $template->addHeaders($this->headers); } // Set the template Request::ini($template); }
/** * Send an authenticated request to the Urban Airship API. The request is * authenticated with the key and secret. * * @param string $method REST method for request * @param mixed $body Body of request, optional * @param string $uri URI for this request * @param string $contentType Content type for the request, optional * @param int $version version # for API, optional, default is 3 * @param mixed $request Request object for this operation (PushRequest, etc) * optional * @return \Httpful\associative|string * @throws AirshipException */ public function request($method, $body, $uri, $contentType = null, $version = 3, $request = null) { $headers = array("Accept" => sprintf(self::VERSION_STRING, $version)); if (!is_null($contentType)) { $headers["Content-type"] = $contentType; } $logger = UALog::getLogger(); $logger->debug("Making request", array("method" => $method, "uri" => $uri, "headers" => $headers, "body" => $body)); if (is_null($request)) { // Tests pass in a pre-built Request. Normal code builds one here. $request = Request::init(); } $request->method($method)->uri($uri)->authenticateWith($this->key, $this->secret)->body($body)->addHeaders($headers); $response = $request->send(); $logger->debug("Received response", array("status" => $response->code, "headers" => $response->raw_headers, "body" => $response->raw_body)); if ($response->code >= 300) { throw AirshipException::fromResponse($response); } return $response; }
public function getHttpXmlInstance($file = "apps.xml") { $headers = "HTTP/1.1 200 OK\n Content-Length: 0\n Server: Roku UPnP/1.0 MiniUPnPd/1.4\r\n"; $response = new \Httpful\Response(file_get_contents(__DIR__ . "/../data/" . $file), $headers, \Httpful\Request::init()); $http = $this->getMock('\\Roku\\Utils\\Http'); // Configure the stub. $http->expects($this->any())->method('get')->will($this->returnValue($response)); $http->expects($this->any())->method('post')->will($this->returnValue($response)); return $http; }
protected function getClient($method) { return Request::init($method)->authenticateWith($this->_username, $this->getAuthenticationToken()); }
/** * 执行http发送请求 * * @throws \Httpful\Exception\ConnectionErrorException */ protected function sendRequest() { !$this->httpful and $this->httpful = Request::init($this->method); $payload = ''; if (in_array($this->httpful->method, ['POST', 'PUT'])) { $payload = $this->makePayload(); } $uri = $this->account->getSchemeHost() . $this->requestResource; $this->urlParams and $uri .= '?' . http_build_query($this->urlParams) and $this->requestResource .= '?' . http_build_query($this->urlParams); $this->httpful->uri($uri); $this->httpful->addHeader('Content-Length', strlen($payload)); $this->httpful->addHeader('Content-MD5', base64_encode(md5($payload))); $this->httpful->addHeader('Content-Type', 'text/xml;utf-8'); $this->httpful->addHeader('Date', date('D, d M Y H:i:s', time()) . ' GMT'); $this->httpful->addHeader('Host', $this->account->getHost()); $this->makeSpecificHeaders(); $this->httpful->body($payload); $this->httpful->addHeader('Authorization', $this->makeSignature()); try { return $this->httpful->send(); } catch (\Exception $e) { return new Response(sprintf(<<<EOF <?xml version="1.0"?> <Error xmlns="http://mqs.aliyuncs.com/doc/v1"> <Code>%s</Code> <Message>%s</Message> <RequestId>0</RequestId> <HostId>%s</HostId> </Error> EOF , $e->getCode(), $e->getMessage() . '; FILE: ' . $e->getFile() . '; LINE: ' . $e->getLine(), $this->account->getSchemeHost()), "HTTP/1.1 400 OK\r\nServer: MOCK-SERVER\r\nContent-Type: text/xml;charset=utf-8\r\nx-mqs-request-id: 0", $this->httpful); } }
/** * Makes a request to the API * * @param string $method * @param string $uri * @param array|null $data * @return Response * @throws \Httpful\Exception\ConnectionErrorException */ public function request($method, $uri, array $data = null) { $signedData = $this->signData($data); $req = Request::init($method)->uri(self::BLIH_BASE_URI . $uri)->autoParse(true)->addHeader("Content-Type", "application/json")->addHeader("User-Agent", "BLIH")->body($signedData, "application/json"); $res = $req->send(); return $res; }
public function testApplyTemplateEmpty() { $client = $this->make_client(); $client->set_template(Request::init()); $this->assertInstanceOf('Httpful\\Request', $client->get_template(), 'Could not set empty Request template.'); }
public function testShorthandMimeDefinition() { $r = Request::init()->expects('json'); $this->assertEquals(Mime::JSON, $r->expected_type); $r = Request::init()->expectsJson(); $this->assertEquals(Mime::JSON, $r->expected_type); }
public function __construct($app_key = null, $secret = null, $base_uri = null) { $this->set_app_key($app_key); $this->set_secret($secret); if ($base_uri != null) { self::$base_uri = $base_uri; } $template = Request::init()->withoutStrictSsl()->expectsJson()->sendsType(Mime::JSON)->addHeader('yotpo_api_connector', 'PHP-' . Yotpo::VERSION); // Set it as a template Request::ini($template); }