/** * @return array */ public function getResults($offset, $itemCountPerPage) { $query = $this->createSearchQuery($offset, $itemCountPerPage); $adapter = new Http\Client\Adapter\Curl(); $adapter->setOptions(array('curloptions' => array(CURLOPT_SSL_VERIFYPEER => false))); $client = new Http\Client(); $client->setAdapter($adapter); $client->setMethod('GET'); $client->setUri($this->getOptions()->getSearchEndpoint() . $query); $response = $client->send(); if (!$response->isSuccess()) { throw new Exception\RuntimeException("Invalid response received from CloudSearch.\n" . $response->getContent()); } $results = Json::decode($response->getContent(), Json::TYPE_ARRAY); $this->count = $results['hits']['found']; if (0 == $this->count) { return array(); } if ($this->getOptions()->getReturnIdResults()) { $results = $this->extractResultsToIdArray($results); } foreach ($this->getConverters() as $converter) { $results = $converter->convert($results); } return $results; }
/** * Efetua consulta de cep. * * @param type $cep * @return type * @throws Exception */ public function addressFromCep($cep) { if (!file_exists(self::CONFIG_FILE)) { throw new Exception("Arquivo de configurações do cliente BYJG não existe"); } $config = (include self::CONFIG_FILE); $result = array('found' => false); try { // Requisicao ao BYJG que prove base de dados gratuita para CEP $byJg = new Client(self::HOST); $byJg->setMethod(Request::METHOD_POST); $byJg->setParameterPost(array('httpmethod' => 'obterlogradouroauth', 'cep' => $cep, 'usuario' => $config['username'], 'senha' => $config['password'])); $response = $byJg->send(); if ($response->isOk()) { // captura resultado e organiza dados $body = preg_replace("/^OK\\|/", "", $response->getBody()); // Separa as partes do CEP $parts = explode(", ", $body); if (count($parts) <= 1) { throw new Exception("Resposta ByJG não pode suprir CEP como esperado"); } $result['found'] = true; list($result['logradouro'], $result['bairro'], $result['cidade'], $result['estado'], $result['codIbge']) = $parts; } } catch (Exception $e) { Firephp::getInstance()->err($e->__toString()); } return $result; }
/** * Constructor * * @param array|Traversable $options */ function __construct($options = array()) { if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } if (!is_array($options)) { throw new Exception\InvalidArgumentException('Invalid options provided'); } $auth = array( 'username' => $options[self::USERNAME], 'password' => $options[self::PASSWORD], 'appKey' => $options[self::APP_KEY], ); $nirvanix_options = array(); if (isset($options[self::HTTP_ADAPTER])) { $httpc = new HttpClient(); $httpc->setAdapter($options[self::HTTP_ADAPTER]); $nirvanix_options['httpClient'] = $httpc; } try { $this->_nirvanix = new NirvanixService($auth, $nirvanix_options); $this->_remoteDirectory = $options[self::REMOTE_DIRECTORY]; $this->_imfNs = $this->_nirvanix->getService('IMFS'); $this->_metadataNs = $this->_nirvanix->getService('Metadata'); } catch (\Zend\Service\Nirvanix\Exception $e) { throw new Exception\RuntimeException('Error on create: '.$e->getMessage(), $e->getCode(), $e); } }
public function findRegion($country, $query) { $request = new Request(); $request->setMethod(Request::METHOD_GET); foreach ($query as $key => $value) { $request->getQuery()->set($key, $value); } $request->getHeaders()->addHeaderLine('Accept', 'application/json'); switch ($country) { case 'CH': $request->setUri($this->config['url'] . '/ch-region'); break; default: $request->setUri($this->config['url'] . '/ch-region'); break; } $client = new Client(); $response = $client->send($request); $body = $response->getBody(); $result = json_decode($body, true); if ($result) { return $result['_embedded']['ch_region']; } /*echo "<textarea cols='100' rows='30' style='position:relative; z-index:10000; width:inherit; height:200px;'>"; print_r($body); echo "</textarea>"; die();*/ return null; }
/** * Fetch Links * * Fetches a set of links corresponding to an OpenURL * * @param string $openURL openURL (url-encoded) * * @return string raw XML returned by resolver */ public function fetchLinks($openURL) { // Make the call to SerialsSolutions and load results $url = $this->baseUrl . (substr($this->baseUrl, -1) == '/' ? '' : '/') . 'openurlxml?version=1.0&' . $openURL; $feed = $this->httpClient->setUri($url)->send()->getBody(); return $feed; }
/** * @return Client */ public function getClient() { $clientOptions = isset($this->options['client']) ? $this->options['client'] : []; $client = new Client(null, $clientOptions); $client->setAdapter(new Client\Adapter\Curl()); return $client; }
public function getServiceConfig() { return array('factories' => array('Search\\GoogleCustomSearch' => function ($services) { $config = $services->get('Config'); if (!isset($config['search'])) { throw new ServiceNotFoundException(sprintf('Unable to create %s; missing configuration key "search", with subkeys "apikey" and "custom_search_identifier"', __NAMESPACE__ . '\\GoogleCustomSearch')); } $config = $config['search']; if (!isset($config['apikey']) || !is_string($config['apikey'])) { throw new ServiceNotFoundException(sprintf('Unable to create %s; missing subkey "apikey"', __NAMESPACE__ . '\\GoogleCustomSearch')); } if (!isset($config['custom_search_identifier']) || !is_string($config['custom_search_identifier'])) { throw new ServiceNotFoundException(sprintf('Unable to create %s; missing subkey "custom_search_identifier"', __NAMESPACE__ . '\\GoogleCustomSearch')); } $queryOptions = isset($config['query_options']) && is_array($config['query_options']) ? $config['query_options'] : array(); $httpClientService = isset($config['http_client_service']) && is_string($config['http_client_service']) ? $config['http_client_service'] : false; if ($httpClientService && $services->has($httpClientService)) { $httpClient = $services->get($httpClientService); } else { $httpClient = new HttpClient(); $httpClient->setOptions(array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'keepalive' => true, 'timeout' => 10)); } $search = new GoogleCustomSearch($httpClient, $config['apikey'], $config['custom_search_identifier'], $queryOptions); if (isset($config['items_per_page'])) { $search->setItemsPerPage($config['items_per_page']); } return $search; })); }
/** * Make a remote call to freegeoip.net to detect country of current customer session and store it into session * * @return $this */ public function saveVisitorData($observer) { $clientIP = $this->_request->getClientIp(); $httpClient = new Client(); $clientIP = $this->getRandomeIp($clientIP); $uri = self::URL_GEO_IP_SITE . $clientIP; $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = JsonDecoder::decode($httpClient->send()->getBody()); $this->_customerSession->setVisitorData($response); //save to database $currenttime = date('Y-m-d H:i:s'); $model = $this->_objectManager->create('Bluecom\\Freegeoip\\Model\\Visitor'); $model->setData('visitor_ip', $response->ip); $model->setData('country_code', $response->country_code); $model->setData('country_name', $response->country_name); $model->setData('region_code', $response->region_code); $model->setData('region_name', $response->region_name); $model->setData('city', $response->city); $model->setData('zip_code', $response->zip_code); $model->setData('latitude', $response->latitude); $model->setData('longitude', $response->longitude); $model->setData('metro_code', $response->metro_code); $model->setData('browser', $_SERVER['HTTP_USER_AGENT']); $model->setData('os', php_uname()); $model->setData('created', $currenttime); $model->save(); } catch (\Exception $e) { $this->_logger->critical($e); } return $this; }
public static function getLatLng($address) { $latLng = []; try { $url = sprintf('http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false', $address); $client = new Client($url); $client->setAdapter(new Curl()); $client->setMethod('GET'); $client->setOptions(['curloptions' => [CURLOPT_HEADER => false]]); $response = $client->send(); $body = $response->getBody(); $result = Json\Json::decode($body, 1); $latLng = ['lat' => $result['results'][0]['geometry']['location']['lat'], 'lng' => $result['results'][0]['geometry']['location']['lng']]; $isException = false; } catch (\Zend\Http\Exception\RuntimeException $e) { $isException = true; } catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $e) { $isException = true; } catch (Json\Exception\RuntimeException $e) { $isException = true; } catch (Json\Exception\RecursionException $e2) { $isException = true; } catch (Json\Exception\InvalidArgumentException $e3) { $isException = true; } catch (Json\Exception\BadMethodCallException $e4) { $isException = true; } if ($isException === true) { //código em caso de problemas no decode } return $latLng; }
/** * Sets request handler * * @param \Zend\Http\Client $handler * @return RemoteCompiler */ public function setRequestHandler($handler) { $this->requestHandler = $handler; $this->requestHandler->setUri($this->url)->setMethod($this->method); $this->requestHandler->getUri()->setPort($this->port); return $this; }
/** * Sets a proper EncType on the given \Zend\Http\Client object (for Xml Request, used value is Client::ENC_URLENCODED) * * @param \Zend\Http\Client $client the Zend http client object * * @return mixed|\Zend\Http\Client */ public function setClientEncType(\Zend\Http\Client $client) { // Setting EncType to UrlEncoded //TODO is it really necessary? xml request should just send some xml code in the body; thus, no need for encryption $client->setEncType(\Zend\Http\Client::ENC_URLENCODED); return $client; }
/** * Fetches the version of the latest stable release. * * @return string */ public static function getLatest() { if (null === self::$latestVersion) { self::$latestVersion = 'not available'; $url = 'https://api.github.com/repos/GotCms/GotCms/git/refs/tags'; try { $client = new Client($url, array('adatper' => 'Zend\\Http\\Client\\Adapter\\Curl', 'timeout' => 2, 'ssltransport' => STREAM_CRYPTO_METHOD_TLS_CLIENT, 'sslverifypeer' => false)); $response = $client->send(); if ($response->isSuccess()) { $content = $response->getBody(); } } catch (\Exception $e) { //Don't care } //Try to retrieve with file_get_contents if (empty($content)) { $content = @file_get_contents($url); } if (!empty($content)) { $apiResponse = Json::decode($content, Json::TYPE_ARRAY); // Simplify the API response into a simple array of version numbers $tags = array_map(function ($tag) { return substr($tag['ref'], 10); // Reliable because we're filtering on 'refs/tags/' }, $apiResponse); // Fetch the latest version number from the array self::$latestVersion = array_reduce($tags, function ($a, $b) { return version_compare($a, $b, '>') ? $a : $b; }); } } return self::$latestVersion; }
/** * @param ProgressAdapter|null $progressAdapter */ public function updateAddressFormats(ProgressAdapter $progressAdapter = null) { $localeDataUri = $this->options->getLocaleDataUri(); $dataPath = $this->options->getDataPath(); $locales = json_decode($this->httpClient->setUri($localeDataUri)->send()->getContent()); foreach (scandir($dataPath) as $file) { if (fnmatch('*.json', $file)) { unlink($dataPath . '/' . $file); } } $countryCodes = isset($locales->countries) ? explode('~', $locales->countries) : []; $countryCodes[] = 'ZZ'; if ($progressAdapter !== null) { $progressBar = new ProgressBar($progressAdapter, 0, count($countryCodes)); } foreach ($countryCodes as $countryCode) { file_put_contents($dataPath . '/' . $countryCode . '.json', $this->httpClient->setUri($localeDataUri . '/' . $countryCode)->send()->getContent()); if (isset($progressBar)) { $progressBar->next(); } } if (isset($progressBar)) { $progressBar->finish(); } // We clearly don't want the "ZZ" in the array! array_pop($countryCodes); $writer = new PhpArrayWriter(); $writer->setUseBracketArraySyntax(true); $writer->toFile($this->options->getCountryCodesPath(), $countryCodes, false); }
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); $client = new Client(); $client->setOptions($config['oauth2']['httpClient']); return $client; }
/** * @param $ipString * @return IdentityInformation * @throws \Zend\Validator\Exception\InvalidArgumentException */ public function getIpInfo($ipString) { $ipValidator = new Ip(); if (!$ipValidator->isValid($ipString)) { throw new InvalidArgumentException(); } // creating request object $request = new Request(); $request->setUri($this->endPoint . $ipString . '/json'); $client = new Client(); $adapter = new Client\Adapter\Curl(); $adapter->setCurlOption(CURLOPT_TIMEOUT_MS, 500); $client->setAdapter($adapter); $response = $client->send($request); $data = $response->getBody(); $dataArray = json_decode($data); $identityInformation = new IdentityInformation(); $identityInformation->setCountry(isset($dataArray->country) ? $dataArray->country : ''); $identityInformation->setRegion(isset($dataArray->region) ? $dataArray->region : ''); $identityInformation->setCity(isset($dataArray->city) ? $dataArray->city : ''); $identityInformation->setLocation(isset($dataArray->loc) ? $dataArray->loc : ''); $identityInformation->setProvider(isset($dataArray->org) ? $dataArray->org : ''); $identityInformation->setHostName(isset($dataArray->hostname) ? $dataArray->hostname : ''); return $identityInformation; }
/** * @dataProvider providerHellCookies() */ public function testZendClient($url) { $client = new Zend_Http_Client(); $client->setUri($url); //$response = $client->request(); $this->markTestIncomplete('This test has not been implemented yet.'); }
/** * Send request elasticsearch like this : * curl -X{$httpMethod} http://host/type/index/{$elasticMethod} -d '{json_decode($content)}' * @param int $httpMethod * @param string $elasticMethod * @param string $content * * @return Stdlib\ResponseInterface */ public function sendRequest($httpMethod = Request::METHOD_GET, $elasticMethod = null, $content = null) { $request = new Request(); $request->setUri($this->url . $elasticMethod)->setMethod($httpMethod)->setContent($content); $client = new Client(); return $client->dispatch($request); }
function setPostRut($ruts) { foreach ($ruts as $rut) { $busqueda[] = explode('-', $rut[0]); } echo '<pre>'; print_r($busqueda); echo '</pre>'; $client = new Client('http://reca.poderjudicial.cl/', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true)); $headers = $client->getRequest()->getHeaders(); $cookies = new Zend\Http\Cookies($headers); $client->setMethod('GET'); $response = $client->send(); $client->setUri('http://reca.poderjudicial.cl/RECAWEB/AtPublicoViewAccion.do?tipoMenuATP=1'); $cookies->addCookiesFromResponse($response, $client->getUri()); $response = $client->send(); $client->setUri("http://reca.poderjudicial.cl/RECAWEB/AtPublicoDAction.do"); foreach ($busqueda as $rut) { $parametros = array('actionViewBusqueda' => '2', 'FLG_Busqueda' => '2', 'FLG_User_Valid' => '0', 'TIP_Lengueta' => 'tdDos', 'COD_Competencia' => 'C', 'tribunal_aux' => '-1', 'username_aux' => '', 'password_aux' => '', 'aux_codlibro' => '', 'aux_rolinterno' => '', 'aux_eracausa' => '', 'aux_codcorte' => '', 'RUT_Cod_Competencia' => 'C', 'RUT_Rut' => $rut[0], 'RUT_Rut_Db' => $rut[1], 'RIT_Cod_Competencia' => '0', 'RIT_Tip_Causa' => '0', 'RIT_Rol_Interno' => '', 'RIT_Era_Causa' => '', 'corte_Cod_Tribunal' => '-1', 'corte_Cod_Libro' => '0', 'corte_Rol_Interno' => '', 'corte_Era_Causa' => '', 'OPC_Cod_Corte' => '-1', 'OPC_Cod_Tribunal' => '-1', 'username' => '', 'password' => ''); $client->setParameterPost($parametros); echo '<pre>'; print_r($parametros); echo '</pre>'; $response = $client->setMethod('POST')->send(); $data = $response->getContent(); echo '<pre>'; print_r($response->getContent()); echo '</pre>'; die; $rut = $rut[0] . '-' . $rut[1]; $dom = new Query($data); $resultados = $dom->execute('#divRecursos tr'); $rols = $this->busquedaRut($resultados, $rut); } }
/** * Add a new subscription * * @return JsonModel */ public function create($data) { $username = $this->params()->fromRoute('username'); $usersTable = $this->getTable('UsersTable'); $user = $usersTable->getByUsername($username); $userFeedsTable = $this->getTable('UserFeedsTable'); $rssLinkXpath = '//link[@type="application/rss+xml"]'; $faviconXpath = '//link[@rel="shortcut icon"]'; $client = new Client($data['url']); $client->setEncType(Client::ENC_URLENCODED); $client->setMethod(\Zend\Http\Request::METHOD_GET); $response = $client->send(); if ($response->isSuccess()) { $html = $response->getBody(); $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"); $dom = new Query($html); $rssUrl = $dom->execute($rssLinkXpath); if (!count($rssUrl)) { throw new Exception('Rss url not found in the url provided', 404); } $rssUrl = $rssUrl->current()->getAttribute('href'); $faviconUrl = $dom->execute($faviconXpath); if (count($faviconUrl)) { $faviconUrl = $faviconUrl->current()->getAttribute('href'); } else { $faviconUrl = null; } } else { throw new Exception("Website not found", 404); } $rss = Reader::import($rssUrl); return new JsonModel(array('result' => $userFeedsTable->create($user->id, $rssUrl, $rss->getTitle(), $faviconUrl))); }
public function getServiceConfig() { return array('factories' => array('Changelog\\XmlRpc\\Client' => function ($services) { $config = $services->get('Config'); if (!isset($config['changelog'])) { throw new RuntimeException('Expecting a "changelog" key in configuration; none found'); } $config = $config['changelog']; if (!isset($config['jira']) || !is_array($config['jira'])) { throw new RuntimeException('Expecting an array of JIRA credentials in "changelog" configuration; none found'); } $jiraUrl = isset($config['jira']['url']) ? $config['jira']['url'] : 'http://framework.zend.com/issues/rpc/xmlrpc'; $cxn = new XmlRpcClient($jiraUrl); $client = $cxn->getProxy('jira1'); return $client; }, 'Changelog\\Jira\\Auth' => function ($services) { $config = $services->get('Config'); if (!isset($config['changelog'])) { throw new RuntimeException('Expecting a "changelog" key in configuration; none found'); } $config = $config['changelog']; if (!isset($config['jira']) || !is_array($config['jira'])) { throw new RuntimeException('Expecting an array of JIRA credentials in "changelog" configuration; none found'); } $jiraCredentials = $config['jira']; $client = $services->get('Changelog\\XmlRpc\\Client'); $auth = $client->login($jiraCredentials['username'], $jiraCredentials['password']); return $auth; }, 'Changelog\\Http\\Client' => function ($services) { $client = new HttpClient(); $client->setOptions(array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'keepalive' => true, 'timeout' => 10)); return $client; })); }
/** * Fetch Links * * Fetches a set of links corresponding to an OpenURL * * @param string $openURL openURL (url-encoded) * * @return string raw XML returned by resolver */ public function fetchLinks($openURL) { // Make the call to SFX and load results $url = $this->baseUrl . '?sfx.response_type=multi_obj_detailed_xml&svc.fulltext=yes&' . $openURL; $feed = $this->httpClient->setUri($url)->send()->getBody(); return $feed; }
/** * @param Struct\SMS $item * @return Client */ protected function makeClient(Struct\SMS $item) { $client = new Client(); $client->setUri($this->prepareUrl($item)); $client->setMethod('GET'); return $client; }
/** * Get Http client * * @param string $url URL * @param bool $resetParams Reset params * @param string $method Method * @param string $adapterName Adapter name * * @return Client */ protected function _getHttpClient($url, $resetParams = false, $method = Request::METHOD_GET, $adapterName = self::CONNECTION_CURL_ADAPTER) { $this->_httpClient = new Client($url); $this->_httpClient->resetParameters($resetParams); $this->_httpClient->setMethod($method)->setAdapter($adapterName); return $this->_httpClient; }
public function scrape($url) { $client = new Client($url); $records = 0; $response = $client->send(); if ($response->isClientError()) { return $records; } $html = $response->getBody(); //$html = $response->getBody(); // although AIM25 is xhtml, it isn't quite valid enough // just to load into a domdocument //$dd = new \DOMDocument(); //if (! $dd->loadHTML($html) ) //{ // return $res; //} //$xp = new \DOMXPath($dd); //$el = $xp->query("//*[@id='content']/h1")->item(0); // so just brute-force it with a regex. Probably much quicker anyway if (preg_match('/ \\((\\d+) matches\\)/', $html, $matches) != 1) { return 0; } return $matches[1]; }
public function pesquisaCep($strCEP) { $httpClient = new Client(); $httpClient->setUri('http://webservice.kinghost.net/web_cep.php')->setParameterGet(array('auth' => $this->auth, 'formato' => 'json', 'cep' => $strCEP)); $response = (object) json_decode($httpClient->send()->getBody(), true); return array('uf' => $response->uf, 'cidade' => $response->cidade, 'bairro' => $response->bairro, 'logradouro' => $response->logradouro, 'status' => $response->resultado ? true : false, 'message' => !$response->resultado ? 'CEP não encontrado' : ''); }
public static function sendRequest($request) { $client = new Client(); $response = $client->send($request); //envoie la requête au service REST return $response; }
public function pharAction() { $client = $this->serviceLocator->get('zendServerClient'); $client = new Client(); if (defined('PHAR')) { // the file from which the application was started is the phar file to replace $file = $_SERVER['SCRIPT_FILENAME']; } else { $file = dirname($_SERVER['SCRIPT_FILENAME']) . '/zs-client.phar'; } $request = new Request(); $request->setMethod(Request::METHOD_GET); $request->setHeaders(Headers::fromString('If-Modified-Since: ' . gmdate('D, d M Y H:i:s T', filemtime($file)))); $request->setUri('https://github.com/zendtech/ZendServerSDK/raw/master/bin/zs-client.phar'); //$client->getAdapter()->setOptions(array('sslcapath' => __DIR__.'/../../../certs/')); $client->setAdapter(new Curl()); $response = $client->send($request); if ($response->getStatusCode() == 304) { return 'Already up-to-date.'; } else { ErrorHandler::start(); rename($file, $file . '.' . date('YmdHi') . '.backup'); $handler = fopen($file, 'w'); fwrite($handler, $response->getBody()); fclose($handler); ErrorHandler::stop(true); return 'The phar file was updated successfully.'; } }
/** * @todo whats wrong with SSL? * @return array */ public function doRequest() { $url = 'https://www.mvg.de/.rest/betriebsaenderungen/api/interruptions'; $client = new Client($url, array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_SSL_VERIFYPEER => FALSE))); $client->setMethod(\Zend\Http\Request::METHOD_GET); return ZendJson::decode($client->send()->getBody()); }
/** * {@inheritdoc} * @see \InoPerunApi\Client\Authenticator\ClientAuthenticatorInterface::configureClient() */ public function configureClient(Http\Client $httpClient) { $keyFile = $this->getOption(self::OPT_KEY_FILE, null, true); $crtFile = $this->getOption(self::OPT_CRT_FILE, null, true); $keyPass = $this->getOption(self::OPT_KEY_PASS); $httpClient->setOptions(array('curloptions' => array(CURLOPT_SSLKEY => $keyFile, CURLOPT_SSLCERT => $crtFile, CURLOPT_SSLKEYPASSWD => $keyPass))); }
protected function getClientUrl(Client $client) { $uri = $client->getUri(); $query = $client->getRequest()->getQuery()->toString(); //$post = $client->getRequest()->getPost()->toString(); return $uri . '?' . $query; }