作者:outeredg
项目:edge-zf
/**
* @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;
}
作者:braghimsistema
项目:zf2li
/**
* 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;
}
作者:necrogam
项目:zf
/**
* 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);
}
}
作者:omusic
项目:casaw
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;
}
作者:till
项目:vufin
/**
* 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;
}
作者:compufou
项目:rdstatio
/**
* @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;
}
作者:Tony13
项目:zf-we
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;
}));
}
作者:kietlu
项目:magento2-backend-trainin
/**
* 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;
}
作者:armeni
项目:armenio-zf2-geolocation-modul
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;
}
作者:neeckelo
项目:ClosureCompilerPH
/**
* 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;
}
作者:msli
项目:remote-hos
/**
* 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;
}
作者:hmschreine
项目:GotCm
/**
* 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;
}
作者:DavidHav
项目:Ajast
/**
* @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);
}
作者:coogl
项目:oauth
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$client = new Client();
$client->setOptions($config['oauth2']['httpClient']);
return $client;
}
作者:arb
项目:MyCod
/**
* @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;
}
作者:eduardohayash
项目:camel-webspide
/**
* @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.');
}
作者:Edenci
项目:GeonamesServe
/**
* 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);
}
作者:jpablocasanuev
项目:pjud_v
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);
}
}
作者:navidnahid
项目:zf2_ap
/**
* 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)));
}
作者:vrkansagar
项目:zf-we
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;
}));
}