public function get($url) { if (!$this->isValidArgument($url)) { throw new \InvalidArgumentException('Supply a valid URL please.'); } return $this->guzzle->get($url); }
/** * Executa uma requisição GET. * * @param $part * @param array $data * @param array $headers * @return mixed */ public function get($part, $data = [], array $headers = []) { $opts = ['headers' => array_merge([], $this->headers, $headers)]; $part = uri_params($part, $data); $response = new Response($this->client->get($part, $opts)); return $response->make(); }
/** * Execute an operaction * * A successful operation will return result as an array. * An unsuccessful operation will return null. * * @param OperationInterface $op * @return array|null */ public function execute(OperationInterface $op) { try { if ($op instanceof DeleteOperationInterface) { $response = $this->httpClient->delete($op->getEndpoint(), ['headers' => $op->getHeaders()]); } elseif ($op instanceof PostOperationInterface) { $response = $this->httpClient->post($op->getEndpoint(), ['headers' => $op->getHeaders(), 'body' => $op->getData()]); } elseif ($op instanceof PatchOperationInterface) { $response = $this->httpClient->patch($op->getEndpoint(), ['headers' => $op->getHeaders(), 'body' => $op->getData()]); } elseif ($op instanceof PutOperationInterface) { $response = $this->httpClient->put($op->getEndpoint(), ['headers' => $op->getHeaders(), 'body' => $op->getData()]); } else { $response = $this->httpClient->get($op->getEndpoint()); } } catch (GuzzleHttp\Exception\ClientException $e) { throw new Exception\ClientException('ClientException occurred in request to Orchestrate: ' . $e->getMessage(), $e->getCode(), $e); } catch (GuzzleHttp\Exception\ServerException $e) { throw new Exception\ServerException('ServerException occurred in request to Orchestrate: ' . $e->getMessage(), $e->getCode(), $e); } $refLink = null; $location = null; if ($response->hasHeader('ETag')) { $refLink = str_replace('"', '', $response->getHeaderLine('ETag')); } elseif ($response->hasHeader('Link')) { $refLink = str_replace(['<', '>; rel="next"'], ['', ''], $response->getHeaderLine('Link')); } if ($response->hasHeader('Location')) { $location = $response->getHeaderLine('Location'); } $rawValue = $response->getBody(true); $value = json_decode($rawValue, true); return $op->getObjectFromResponse($refLink, $location, $value, $rawValue); }
/** * @since 0.2 * @param Request $request * @return mixed */ public function getRequest(Request $request) { $resultArray = $this->client->get(null, array('query' => array_merge($request->getParams(), array('format' => 'json')), 'headers' => $request->getHeaders()))->json(); $this->triggerErrors($resultArray); $this->throwUsageExceptions($resultArray); return $resultArray; }
/** * @param string $vhost * @param string $name * @param int $interval * * @return array */ public function getQueue($vhost, $name, $interval = 30) { $queueName = sprintf('%s/%s', urlencode($vhost), urlencode($name)); $url = sprintf('http://%s:%d/api/queues/%s?%s', $this->hostname, $this->port, $queueName, http_build_query(['lengths_age' => $interval, 'lengths_incr' => $interval, 'msg_rates_age' => $interval, 'msg_rates_incr' => $interval, 'data_rates_age' => $interval, 'data_rates_incr' => $interval])); $response = $this->httpClient->get($url, ['auth' => [$this->user, $this->password]]); return $response->json(); }
/** * {@inheritdoc} */ public function denormalize($data, $class, $format = NULL, array $context = array()) { $file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody(); $path = 'temporary://' . drupal_basename($data['uri'][0]['value']); $data['uri'] = file_unmanaged_save_data($file_data, $path); return $this->entityManager->getStorage('file')->create($data); }
/** * Download a package file. * * @param string $path * @param string $url * @param string $shasum */ public function downloadFile($path, $url, $shasum = '') { $file = $path . '/' . uniqid(); try { $data = $this->client->get($url)->getBody(); if ($shasum && sha1($data) !== $shasum) { throw new ChecksumVerificationException("The file checksum verification failed"); } if (!$this->files->makeDir($path) || !$this->files->putContents($file, $data)) { throw new NotWritableException("The path is not writable ({$path})"); } if (Zip::extract($file, $path) !== true) { throw new ArchiveExtractionException("The file extraction failed"); } $this->files->delete($file); } catch (\Exception $e) { $this->files->delete($path); if ($e instanceof TransferException) { if ($e instanceof BadResponseException) { throw new UnauthorizedDownloadException("Unauthorized download ({$url})"); } throw new DownloadErrorException("The file download failed ({$url})"); } throw $e; } }
/** * Scrape and fetch page content for the provided link * * @param $link * @return string */ public function fetchPageContentFor($link) { // We need to enable cookie to be able to get the proper page source $cookieJar = new CookieJar(); $response = $this->guzzleClient->get($link, ['cookies' => $cookieJar]); return (string) $response->getBody(); }
/** * Return all the tasks of a given list * * @param int $list_id * * @return array() */ public function getListTasks($list_id) { if (!is_numeric($list_id)) { throw new \InvalidArgumentException('The list id must be numeric.'); } $response = $this->client->get('tasks', ['query' => ['list_id' => $list_id]]); $this->checkResponseStatusCode($response, 200); return json_decode($response->getBody()); }
/** * @param $url * @return string * @throws HttpClientException */ public function download($url) { $response = $this->guzzlClient->get($url); if (200 == $response->getStatusCode()) { $body = $response->getBody(); return $this->saveBodyAsFile($body); } throw new HttpClientException(sprintf('Unable to get download from "%s"', $url)); }
/** * @param $action * @param array $options * @return mixed * @throws \Exception */ public function get($action, array $options) { $requestOptions = $this->buildRequestOptions($action, $options); try { $response = $this->connection->get($this->api_url, ['headers' => $requestOptions['headers'], 'cookies' => $requestOptions['cookies'], 'query' => $requestOptions['query']]); } catch (RequestException $e) { throw new \Exception($e->getMessage(), $e->getCode(), $e); } return $response->json(); }
/** * send a request to pugme api * * @param string $url * @return mixed * @throws PugNotFoundException */ private function sendRequest($url) { try { $response = $this->client->get($this->baseUrl . $url); $pug = json_decode($response->getBody(), true); } catch (Exception $e) { throw new PugNotFoundException(); } return $pug; }
/** * Fetch the media items. * * @param string $user * * @throws \Vinkla\Instagram\InstagramException * * @return array */ public function get(string $user) : array { try { $url = sprintf('https://www.instagram.com/%s/media', $user); $response = $this->client->get($url); return json_decode((string) $response->getBody(), true)['items']; } catch (RequestException $e) { throw new InstagramException(sprintf('The user [%s] was not found.', $user)); } }
public function profileApi($uuid) { $response = $this->client->get(sprintf(static::PROFILE_API, $uuid))->json(array('object' => true)); if (!$response) { throw new \RuntimeException('Bad UUID ' . $uuid); } elseif (isset($response->error)) { throw new \RuntimeException('Error from API: ' . $response->error . ' on UUID ' . $uuid); } return $response; }
/** * {@inheritdoc} */ public function get($url) { try { $this->response = $this->client->get($url); } catch (RequestException $e) { $this->response = $e->getResponse(); $this->handleError(); } return $this->response->getBody(); }
/** * {@inheritdoc} */ public function fetchProjectData(array $project, $site_key = '') { $url = $this->buildFetchUrl($project, $site_key); $data = ''; try { $data = $this->httpClient->get($url, array('headers' => array('Accept' => 'text/xml')))->getBody(TRUE); } catch (RequestException $exception) { watchdog_exception('update', $exception); } return $data; }
/** * {@inheritdoc} */ public function getEmbedObject($url) { $embed = NULL; try { $response = $this->httpClient->get($this->getEmbedProviderURL($url), array('headers' => array('content-type' => 'application/json'))); $embed = json_decode($response->getBody()); } catch (GuzzleClientException $e) { watchdog_exception('ckeditor_media_embed', $e); } return $embed; }
/** * @param string $vhost * @param string $name * @param int $interval * * @return array */ public function getQueue($vhost, $name, $interval = 30) { $queueName = sprintf('%s/%s', urlencode($vhost), urlencode($name)); $url = sprintf('http://%s:%d/api/queues/%s?%s', $this->hostname, $this->port, $queueName, http_build_query(['lengths_age' => $interval, 'lengths_incr' => $interval, 'msg_rates_age' => $interval, 'msg_rates_incr' => $interval, 'data_rates_age' => $interval, 'data_rates_incr' => $interval])); $options = ['auth' => [$this->user, $this->password]]; if (version_compare(ClientInterface::VERSION, '6.0') >= 0) { $response = $this->httpClient->request('get', $url, $options); } else { $response = $this->httpClient->get($url, $options); } return \GuzzleHttp\json_decode($response->getBody()->getContents(), true); }
/** * {@inheritdoc} */ public function getEmbedObject($url) { $embed = NULL; try { $response = $this->httpClient->get($this->getEmbedProviderURL($url), ['headers' => ['content-type' => 'application/json']]); $embed = json_decode($response->getBody()); } catch (TransferException $e) { drupal_set_message(t('Unable to retrieve @url at this time, please check again later.', ['@url' => $url]), 'warning'); watchdog_exception('ckeditor_media_embed', $e); } return $embed; }
function getMetar($code) { $response = $this->client->get(sprintf(self::METAR_URL, $code)); if (!$response || $response->getStatusCode() >= 400) { throw new RuntimeException("Received {$response->getStatusCode()} response from the server!"); } $crawler = new Crawler($response->getBody()->getContents()); $metar = $crawler->filter('td > font')->text(); if (!$metar) { throw new RuntimeException('Got empty result processing the dataset!'); } return $metar; }
/** * @param array $requestOptions * @return ResponseInterface * @throws TransferException */ public function get(array $requestOptions) { try { $poolIndex = array_rand(self::$serverPool); return $this->guzzleClient->get(self::$serverPool[$poolIndex], $requestOptions); } catch (RequestException $e) { if ($e->getResponse()) { throw $e; } } // There is no server response (timeout, DNS failure); try again. $poolIndex = ($poolIndex + 1) % count(self::$serverPool); return $this->guzzleClient->get(self::$serverPool[$poolIndex], $requestOptions); }
/** * Download Gravatar image and store it to the user upload directory. * * @param $email * @return string path to downloaded image, relative to the storage directory */ public function downloadGravatarImage($email) { try { $gravatarUrl = $this->generateGravatarUrl($email); $response = $this->httpClient->get($gravatarUrl); $avatarPath = $this->generateAvatarPath($response->getHeader('Content-Type')); $this->fileUploadService->storeImage($avatarPath, $response->getBody()); return $avatarPath; } catch (\Exception $e) { // If Guzzle throws an error, then most likely because you're // developing CampaignChain offline. Hence, don't worry about the // error. } }
/** * {@inheritdoc} */ public function get($url = null, $headers = []) { try { $response = $this->guzzleClient->get($url, ['headers' => $headers]); } catch (\Exception $e) { /** @var $e GuzzleClientException */ $body = ''; if ($e->hasResponse()) { $body = (string) $e->getResponse()->getBody(); } throw new RequestException($e->getMessage(), $e->getCode(), $e, $body); } return new Response($response->getStatusCode(), $response->getHeaders(), (string) $response->getBody()); }
/** * @param string $url * @param array $options * * @return array */ protected function makeRequest($url, array $options = []) { if ($this->client === null) { $this->client = new GuzzleClient(); } $item = null; if ($this->cache !== null) { $item = $this->cache->getItem($this->getRequestKey($url, $options)); $data = $item->get(); if ($item->isHit() === true) { $options = array_replace_recursive($options, ['headers' => ['If-Modified-Since' => $data['modified']]]); } } $options = array_replace_recursive($options, ['headers' => ['Accept' => 'application/json', 'Accept-Encoding' => 'gzip', 'User-Agent' => $this->getUserAgent()], 'query' => ['apikey' => $this->apiKey, 'locale' => $this->region->getLocale()], 'timeout' => 60]); try { $response = $this->client->get($url, $options); } catch (ClientException $exception) { switch ($exception->getCode()) { case 404: return; default: $data = json_decode($exception->getResponse()->getBody(), true); throw new BattleNetException($data['detail'], $exception->getCode()); } } return $this->handleSuccessfulResponse($response, $item); }
/** * Sends a request to the Nexmo API * * @param array $query The query parameters * * @return Response * @throws Exception\Exception */ protected function send(array $query) { if (!$this->key || !$this->secret || !$this->from) { throw new Exception\ConfigurationException("Invalid configuration. Missing key, secret, or from."); } $query["api_key"] = $this->key; $query["api_secret"] = $this->secret; $query["from"] = $this->from; $query["status-report-req"] = $this->status_report_req; if ($this->ttl) { $query["ttl"] = $this->ttl; } $response = $this->guzzle->get(self::API_URI, ["query" => $query])->json(); /** * @var Message[] $messages * @var Exception\Exception[] $exceptions */ $messages = []; $exceptions = []; foreach ($response["messages"] as $message) { if ($message["status"] != 0) { $exceptions[] = Exception\Factory::factory($message["error-text"], $message["status"]); } else { $messages[] = new Message($message); } } $response = new Response($messages, $exceptions); if ($exceptions) { $exceptions[0]->setResponse($response); throw $exceptions[0]; } return $response; }
/** * Will download a file from the Telegram server. Before calling this function, you have to call the getFile method! * * @see unreal4u\TelegramAPI\Telegram\Types\File * @see unreal4u\TelegramAPI\Telegram\Methods\GetFile * * @param File $file * @return TelegramDocument */ public function downloadFile(File $file) : TelegramDocument { $this->logger->debug('Downloading file from Telegram, creating URL'); $url = 'https://api.telegram.org/file/bot' . $this->botToken . '/' . $file->file_path; $this->logger->debug('About to perform request to begin downloading file'); return new TelegramDocument($this->httpClient->get($url)); }
/** * @param string $url Url xml souboru, ktery chceme stahnout. * * @return string Stazeny xml soubor zkonvertovany na kodovani utf-8. */ private function downloadXml($url) { $response = $this->httpClient->get($url); $xml = $response->getBody(); $xml = iconv("windows-1250", "utf-8", $xml); $xml = str_replace('encoding="windows-1250"', 'encoding="utf-8"', $xml); return $xml; }
/** * Helper method to get results even when the world is against you... I AM NOT DRAMATIC * * @param string $url * @param Query $query * * @return ResponseInterface */ protected function fetchResponse($url, $query) { try { $response = $this->client->get($url, ['query' => $query->toArray()]); } catch (\GuzzleHttp\Exception\ServerException $e) { $response = $this->fetchResponse($url, $query); } return $response; }
/** * Downloads a torrent file. * * @param TokenInterface $token * @param int $torrentId * @return File */ public function download(TokenInterface $token, $torrentId) { $response = $this->httpClient->get('/torrents/download/' . $torrentId, ['headers' => ['Authorization' => $token->getToken()]]); $contentDispositionHeader = $response->getHeader('Content-Disposition'); preg_match('/filename="(.*)"/', $contentDispositionHeader, $matches); $filename = $this->config['torrent_files_path'] . '/' . $matches[1]; $this->fs->dumpFile($filename, $response->getBody()->getContents(), 0660); return new File($filename, false); }
/** * Sends a message. * * @param string $id * @param string $to * @param string $body * * @throws InvalidRequestInternalException If the request is invalid. * Maybe the api changed? * @throws InvalidParameterInternalException If some parameter is invalid * @throws InsufficientCreditInternalException If credit is insufficient */ public function send($id, $to, $body) { $to = str_replace('+', '', $to); $url = sprintf("%s?username=%s&password=%s&destination=%s&sender=%s&body=%s&reference=%s&dlr=1", $this->url, $this->username, $this->password, $to, $this->generateNumberInternalWorker->generate(false), urlencode(mb_convert_encoding($body, 'ISO-8859-1', 'auto')), $id); $response = $this->client->get($url); if ($response->getBody() != '01') { switch ($response->getBody()) { case '100': throw new InvalidRequestInternalException(sprintf("Operator returned: \"Parameter(s) are missing.\". Request url was:\r\n%s", $url)); case '110': throw new InvalidRequestInternalException(sprintf("Operator returned: \"Bad combination of parameters.\". Request url was:\r\n%s", $url)); case '120': throw new InvalidParameterInternalException(); case '130': throw new InsufficientCreditInternalException(); } } }