本文整理汇总了PHP中Zend\Http\Client类的典型用法代码示例。如果您正苦于以下问题:PHP Client类的具体用法?PHP Client怎么用?PHP Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getResults
/**
* @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;
}
示例2: addressFromCep
/**
* 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;
}
示例3: array
/**
* 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);
}
}
示例4: findRegion
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;
}
示例5: fetchLinks
/**
* 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;
}
示例6: getClient
/**
* @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;
}
示例7: getServiceConfig
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;
}));
}
示例8: saveVisitorData
/**
* 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;
}
示例9: getLatLng
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;
}
示例10: setRequestHandler
/**
* 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;
}
示例11: setClientEncType
/**
* 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;
}
示例12: getLatest
/**
* 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;
}
示例13: updateAddressFormats
/**
* @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);
}
示例14: createService
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$client = new Client();
$client->setOptions($config['oauth2']['httpClient']);
return $client;
}
示例15: getIpInfo
/**
* @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;
}