protected function execute(InputInterface $input, OutputInterface $output) { $config = $this->setConfiguraton($input); $client = new \GuzzleHttp\Client(['defaults' => ['allow_redirects' => false, 'timeout' => 5, 'connect_timeout' => 5]]); /** @var Instance $instance */ foreach ($config->getInstances() as $instance) { $requests[] = $client->createRequest('HEAD', $instance->getUrl()); } $options = []; Pool::send($client, $requests, ['complete' => function (CompleteEvent $event) { }, 'error' => function (ErrorEvent $event) use($config) { $instance = $config->findInstanceByUrl($event->getRequest()->getUrl()); if ($instance == null) { throw new \RuntimeException('Instance not found'); } if (!$event->getException()->hasResponse()) { $raven = new \Raven_Client($instance->getSentryDsn()); $event_id = $raven->getIdent($raven->captureMessage(sprintf('The website %s with url -> %s is down or has a problem', $instance->getName(), $event->getRequest()->getUrl()), [], \Raven_Client::FATAL)); if ($raven->getLastError() !== null) { printf('There was an error sending the event to Sentry: %s', $raven->getLastError()); } $error_handler = new \Raven_ErrorHandler($raven); $error_handler->registerExceptionHandler(); $error_handler->registerErrorHandler(); $error_handler->registerShutdownFunction(); } }]); }
/** * Make API request. * * @throws \Exception * * @param string $method HTTP method [GET / POST / PUT / DELETE]. * @param string $endpoint API endpoint. * @param array $data The request body. * @param Pagination $pagination Set pagination values. * * @return boolean|array */ public function request($method, $endpoint, array $data = array(), Pagination $pagination = null) { $headers = array('Content-Type' => 'application/json', 'Accept' => 'application/json'); if ($pagination instanceof Pagination) { $headers['Range'] = 'records=' . $pagination->getStart() . '-' . $pagination->getEnd(); } $client = new \GuzzleHttp\Client(); $request = $client->createRequest($method, $this->apiUrl . $endpoint, array('body' => !empty($data) ? json_encode($data) : null, 'headers' => $headers)); try { $response = $client->send($request); $body = $response->json(); return $body; } catch (RequestException $e) { $response = $e->getResponse(); $body = $response->json(); switch ((int) $response->getStatusCode()) { case 400: throw new Exception\ValidationException($body['results']['error']['message']); break; case 401: throw new Exception\AuthenticationException('Failed authentication.'); break; case 402: throw new Exception\PaymentRequiredException('Payment required.'); break; case 404: throw new Exception\NotFoundException('Resource not found.'); break; case 500: throw new Exception\ServerException('Server error.'); break; } } return false; }
/** * */ public function call($verb, $host, $port, $uri, $headers = null, $query = null, $body = null, $statusCode = null) { // Fix headers, query and body $headers = \z\conf($headers); $query = \z\conf($query); if (is_null($body) === true) { $body = ''; } // Body must be a string if (is_string($body) === false) { \z\e(EXCEPTION_HTTP_BODY_NOT_VALID, ['body' => json_encode($body, true), 'type' => gettype($body)]); } // Build the HTTP client $client = new \GuzzleHttp\Client(['base_url' => $host]); // Build the request $request = $client->createRequest($verb, $uri, ['exceptions' => false]); // Setup the request $request->setPort($port); $request->setHeaders($headers); $request->setQuery($query); $request->setBody(\GuzzleHttp\Stream\Stream::factory($body)); // Log \z\logger()->debug($request); // Send the request $response = $client->send($request); // Log \z\logger()->debug($response); // Did it succeed? if (is_null($statusCode) === false && (int) $statusCode !== (int) $response->getStatusCode()) { \z\e(EXCEPTION_HTTP_STATUS_CODE_NOT_VALID, ['expected' => $statusCode, 'actual' => $response->getStatusCode(), 'request' => $request->__toString(), 'response' => $response->__toString()]); } // Build the result $result = $response->getBody(); return $result; }
/** * Loads home page * this twig file is found at /www/app/Resource/ * not in the actual src/AppBundle file structure */ public function indexAction(Request $request) { header('Content-Type: text/plain'); $client = new \GuzzleHttp\Client(['base_uri' => 'http://149.210.236.249', 'defaults' => ['headers' => ['Authorization' => 'Token 90f44a24a6bd93a8ca9c21d0b9e0d81d5ab20da2']]]); $request = $client->createRequest("GET", 'http://149.210.236.249/positions'); $request->setPort(8000); return $this->render('AppBundle::layout.html.twig'); }
public function testHMAC() { $context = new Context(array('keys' => array('pda' => 'secret'), 'algorithm' => 'hmac-sha256', 'headers' => array('(request-target)', 'date'))); $client = new \GuzzleHttp\Client(['auth' => 'http-signatures']); $client->getEmitter()->attach(new RequestSubscriber($context)); $message = $client->createRequest('GET', '/path?query=123', array('headers' => array('date' => 'today', 'accept' => 'llamas'))); $context->signer()->sign(new Message($message)); $expectedString = implode(',', array('keyId="pda"', 'algorithm="hmac-sha256"', 'headers="(request-target) date"', 'signature="SFlytCGpsqb/9qYaKCQklGDvwgmrwfIERFnwt+yqPJw="')); $this->assertEquals($expectedString, (string) $message->getHeader('Signature')); }
public function fire() { // get last update $latestLog = DB::table('steam_log')->orderBy('updated', 'DESC')->first(); if (count($latestLog) == 0) { // create new record for player DB::table('steam_log')->insert(['steam_id' => env('STEAM_ID'), 'in_game' => 0, 'updated' => time()]); $currentStatus = 0; } else { $currentStatus = $latestLog->in_game; } $client = new \GuzzleHttp\Client(); $request = $client->createRequest('GET', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . env('STEAM_KEY') . '&steamids=' . env('STEAM_ID')); $response = $client->send($request); $responseData = json_decode($response->getBody()->getContents()); $player = $responseData->response->players[0]; //dd(isset($player->gameid)); if (isset($player->gameid)) { // in game $status = 1; $game_id = $player->gameid; $game_name = $player->gameextrainfo; } else { // out of game $status = 0; $game_id = null; $game_name = null; } // save latest status DB::table('steam_log')->where('steam_id', env('STEAM_ID'))->update(['in_game' => $status, 'game_id' => $game_id, 'game_name' => $game_name, 'updated' => time()]); // check to see if notification needs to be sent if ($currentStatus != $status) { if ($status == 1) { $pushMessage = 'In Game: ' . $game_name; } else { $pushMessage = 'No longer playing game'; } if (env('STEAM_NOTIFY_METHOD') == 'pushover') { // send to Pushover curl_setopt_array($ch = curl_init(), array(CURLOPT_URL => "https://api.pushover.net/1/messages.json", CURLOPT_POSTFIELDS => array("token" => env('PUSHOVER_API_KEY'), "user" => env('PUSHOVER_USER_KEY'), "message" => $pushMessage), CURLOPT_SAFE_UPLOAD => true)); curl_exec($ch); curl_close($ch); } else { // send to Slack $settings = ['username' => env('STEAM_SLACK_USERNAME'), 'channel' => '#' . env('STEAM_SLACK_CHANNEL'), 'link_names' => true, 'icon' => ':ghost:']; // send to slack $client = new \Maknz\Slack\Client(env('STEAM_SLACK_WEBHOOK'), $settings); $client->send($pushMessage); } } $this->info('Complete'); }
public function getEvents() { $client = new \GuzzleHttp\Client(); $request = $client->createRequest('GET', 'https://www.eventbriteapi.com/v3/users/me/owned_events/'); $request->setHeader('Authorization', 'Bearer ' . $this->oauth); $response = $client->send($request); $body = json_decode($response->getBody()); if (isset($body->events) && is_array($body->events)) { $events = array_map(function ($event) { return new \PhpDorset\Eventbrite\EventDecorator($event); }, $body->events); return $events; } return null; }
/** * @param string $method * @param string $url * @param string|null $query * @return string * @throws EntityValidationException */ private function request($method, $url, $query = null) { try { $client = new \GuzzleHttp\Client(['defaults' => ['timeout' => 60, 'allow_redirects' => false, 'verify' => true]]); $options = ['auth' => [$this->user, $this->password, "Digest"]]; if (!empty($query)) { $options['query'] = $query; } $request = $client->createRequest($method, $url, $options); $response = $client->send($request); if ($response->getStatusCode() == 200) { return $response->getBody()->getContents(); } throw new Exception(); } catch (Exception $ex) { SS_Log::log($ex, SS_Log::ERR); throw new EntityValidationException([['message' => 'server error']]); } }
<?php require "../vendor/autoload.php"; // pull the access creds from another file require "github_access_token.php"; $url = "https://api.github.com/gists/bf6c595b6686d38f44ab/star"; $client = new GuzzleHttp\Client(); $request = $client->createRequest('PUT', $url); $request->setHeader("Authorization", "token " . $gh_key); $request->setHeader("Content-Length", "0"); $response = $client->send($request); echo $response->getStatusCode();
<?php require "../vendor/autoload.php"; // register an empty endpoint to begin: http://respondto.it $url = "http://respondto.it/my-endpoint"; $client = new \GuzzleHttp\Client(); // $client->get($url); // with headers and data $request = $client->createRequest('POST', $url . "?page=4"); $request->setHeader("Authorization", "token abcd1234"); $request->setHeader("User-Agent", "GuzzlePHP"); $requestBody = $request->getBody(); $requestBody->setField("name", "Camilla"); $requestBody->setField("species", "Camel"); $response = $client->send($request);
/** * @Then As :user edit the last created comment and set text to :text it should return :statusCode */ public function asEditTheLastCreatedCommentAndSetTextToItShouldReturn($user, $text, $statusCode) { $client = new \GuzzleHttp\Client(); $options = []; $options['auth'] = [$user, '123456']; $options['body'] = '<?xml version="1.0"?> <d:propertyupdate xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"> <d:set> <d:prop> <oc:message>' . $text . '</oc:message> </d:prop> </d:set> </d:propertyupdate>'; try { $res = $client->send($client->createRequest('PROPPATCH', $this->baseUrl . '/remote.php/dav/comments/files/' . $this->fileId . '/' . $this->commentId, $options)); } catch (\GuzzleHttp\Exception\ClientException $e) { $res = $e->getResponse(); } if ($res->getStatusCode() !== (int) $statusCode) { throw new \Exception("Response status code was not {$statusCode} (" . $res->getStatusCode() . ")"); } }
$_date = "{$_date[2]}-{$_date[1]}-{$_date[0]}"; // creating the time zone $zone = new DateTimeZone($config['time_zone']); $i = 0; foreach (glob($path . '/*') as $post) { // getting the time from the filename $time = str_replace('.', ':', pathinfo($post)['filename']); // creating the client $client = new GuzzleHttp\Client(); // creating the correct date $date = new DateTime($_date . ' ' . $time, $zone); // applying the timezone $date->setTimezone($zone); // getting timestamp $posttime = $date->getTimestamp(); // creating the request $request = $client->createRequest('POST', $config['api_url']); $postBody = $request->getBody(); // setting al the values for the request $postBody->setField('key', $config['api_key']); $postBody->setField('id', $config['queue_id']); $postBody->setField('msg', $config['message']); $postBody->setField('posttime', $posttime); // attaching the file $postBody->addFile(new GuzzleHttp\Post\PostFile('media', fopen($post, 'r'))); // posting $response = $client->send($request); $i++; } } echo 'done!' . "\n";
/** * The base request method for all API access. * * @param string $method The request VERB to use (GET, POST, PUT, DELETE) * @param string $path The API path. * @param array $body The content to be used (either as the query, or the json post/put body) * @return object */ protected function processRestRequest($method = NULL, $path = NULL, $body = NULL) { $client = new \GuzzleHttp\Client(array('defaults' => array('exceptions' => false, 'timeout' => $this->timeout))); $url = PostmarkClientBase::$BASE_URL . $path; $options = array(); if ($body != NULL) { $cleanParams = array(); foreach ($body as $key => $value) { if ($value !== NULL) { $cleanParams[$key] = $value; } } switch ($method) { case 'GET': case 'HEAD': case 'DELETE': case 'OPTIONS': $options['query'] = $cleanParams; break; case 'PUT': case 'POST': case 'PATCH': $options['json'] = $cleanParams; break; } } if (PostmarkClientBase::$CERTIFICATE_PATH != NULL) { $options['verify'] = PostmarkClientBase::$CERTIFICATE_PATH; } $request = $client->createRequest($method, $url, $options); $v = $this->version; $o = $this->os; //TODO: include version info in the request. $request->setHeader('User-Agent', "Postmark-PHP (PHP Version:{$v}, OS:{$o})"); $request->setHeader('Accept', 'application/json'); $request->setHeader('Content-Type', 'application/json'); $request->setHeader($this->authorization_header, $this->authorization_token); $response = $client->send($request); $result = NULL; switch ($response->getStatusCode()) { case 200: $result = $response->json(); break; case 401: $ex = new PostmarkException(); $ex->message = 'Unauthorized: Missing or incorrect API token in header. ' . 'Please verify that you used the correct token when you constructed your client.'; $ex->httpStatusCode = 401; throw $ex; break; case 422: $ex = new PostmarkException(); $body = $response->json(); $ex->httpStatusCode = 422; $ex->postmarkApiErrorCode = $body['ErrorCode']; $ex->message = $body['Message']; throw $ex; break; case 500: $ex = new PostmarkException(); $ex->httpStatusCode = 500; $ex->message = 'Internal Server Error: This is an issue with Postmark’s servers processing your request. ' . 'In most cases the message is lost during the process, ' . 'and Postmark is notified so that we can investigate the issue.'; throw $ex; break; } return $result; }
<?php require __DIR__ . '/../vendor/autoload.php'; $httpClient = new GuzzleHttp\Client(); $request = $httpClient->createRequest('GET', 'http://httpbin.org/get'); $response = $httpClient->send($request); echo "REQUEST:\n\n{$request}\n"; echo "RESPONSE:\n\n{$response}\n";
<?php /* Template Name: Hub Pos Test */ $options = get_option(\Tls\TlsHubSubscriber\TlsHubSubscriberWP::get_option_name()); $guzzleClient = new \GuzzleHttp\Client(); // Start empty $hubUrl variable $hubUrl = ''; $callbackUrl = site_url() . '/pushfeed/' . $options['subscription_id']; // Check if the Hub URL finishes with a / or not to be able to create the correct subscribe URL if (preg_match("/\\/\$/", $options['hub_url'])) { $hubUrl = $options['hub_url']; } else { $hubUrl = $options['hub_url']; } // Json Data needed to send to the Hub for Subscription $subscribeJson = json_encode(array("callbackUrl" => esc_url($callbackUrl), "topicId" => esc_url($options['topic_url'])), JSON_UNESCAPED_SLASHES); $subscribeRequest = $guzzleClient->createRequest('POST', $hubUrl); $subscribeRequest->setHeader('Content-Type', 'application/json'); $subscribeRequest->setBody(\GuzzleHttp\Stream\Stream::factory($subscribeJson)); $subscribeResponse = $guzzleClient->send($subscribeRequest);
public function performBatch() { $client = new \GuzzleHttp\Client(array(), array()); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; // does the batch operations $responses = array(); $requests = array(); $this->logger->log(sprintf("starting batch"), DestinyLogger::debug); foreach ($this->batch_items as $xlc) { $headers = $xlc->xlcObject->headers; $url = $xlc->url; $post_data = $xlc->post_data; if ($post_data) { $this->logger->log(sprintf("adding post '%s' to batch", $url), DestinyLogger::debug); $req = $client->createRequest('POST', $url, array('future' => false, 'debug' => false, 'body' => $post_data)); } else { $this->logger->log(sprintf("adding get '%s' to batch", $url), DestinyLogger::debug); $req = $client->createRequest('GET', $url, array('future' => false, 'debug' => false)); } foreach ($headers as $header => $value) { $req->setHeader($header, $value); } $requests[] = $req; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $results = \GuzzleHttp\Pool::batch($client, $requests); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round($finish - $start, 3); $this->logger->log(sprintf("batch of %s took %ss", count($requests), $total_time), DestinyLogger::debug); foreach ($results->getSuccessful() as $response) { $responses[] = array('body' => $response->getBody(), 'request' => $response->getEffectiveUrl()); } foreach ($results->getFailures() as $failures) { dpm($failures); } unset($this->batch_items); return $responses; }