/** * Get Country User * * @param EventObserver $observer */ public function execute(EventObserver $observer) { if (!$this->_customerSession->getLocated()) { //$clientIP = $this->_request->getClientIp(); /* * Set static Ip to test * * DE : 194.55.30.46 * VN : 123.30.215.27 * PL : 212.77.98.9 * SG : 202.157.143.72 * **/ $clientIP = '123.30.215.27'; $uri = 'http://freegeoip.net/json/' . $clientIP; $httpClient = new \Zend\Http\Client(); $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = \Zend\Json\Decoder::decode($httpClient->send()->getBody()); $this->_customerSession->setLocationData($response); $this->_customerSession->setLocated(true); } catch (\Exception $e) { $this->_logger->critical($e); } } }
public function __invoke($par) { $config = $this->getController()->getServiceLocator()->get('config'); $lang = $this->getController()->getEvent()->getRouteMatch()->getParam('lang', 'en'); if (empty($config['geocoder_photon_url'])) { throw new \InvalidArgumentException('Now Service-Adress for Geo-Service available'); } $client = new \Zend\Http\Client($config['geocoder_photon_url']); $client->setMethod('GET'); $osmTags = ['tourism', 'aeroway', 'railway', 'amenity', 'historic', 'tunnel', 'mountain_pass', 'leisure', 'natural', 'bridge', 'waterway']; $osmTags = array_map(function ($i) { return urlencode('!' . $i); }, $osmTags); $uri = sprintf('%s?q=%s&lang=%s&osm_tag=%s', $config['geocoder_photon_url'], urlencode($par), $lang, implode('&osm_tag=', $osmTags)); $client->setUri($uri); $response = $client->send(); $result = $response->getBody(); $result = json_decode($result); $result = $result->features; foreach ($result as $key => $val) { $row = ['name' => property_exists($val->properties, 'name') ? $val->properties->name : '', 'postcode' => property_exists($val->properties, 'postcode') ? $val->properties->postcode : '', 'city' => property_exists($val->properties, 'city') ? $val->properties->city : '', 'street' => property_exists($val->properties, 'street') ? $val->properties->street : '', 'state' => property_exists($val->properties, 'state') ? $val->properties->state : '', 'country' => property_exists($val->properties, 'country') ? $val->properties->country : '', 'coordinates' => implode(":", $val->geometry->coordinates), 'osm_key' => property_exists($val->properties, 'osm_key') ? $val->properties->osm_key : '', 'osm_value' => property_exists($val->properties, 'osm_value') ? $val->properties->osm_value : '', 'osm_id' => property_exists($val->properties, 'osm_id') ? $val->properties->osm_id : '', 'data' => json_encode($val)]; $r[] = $row; } return $r; }
private function getTransports() { $browserSocket = new \Buzz\Browser(); $browserSocket->setClient(new \Buzz\Client\FileGetContents()); $zendFrameworkOneHttpClientSocket = new \Zend_Http_Client(); $zendFrameworkOneHttpClientSocket->setAdapter(new \Zend_Http_Client_Adapter_Socket()); $zendFrameworkOneHttpClientProxy = new \Zend_Http_Client(); $zendFrameworkOneHttpClientProxy->setAdapter(new \Zend_Http_Client_Adapter_Proxy()); $zendFrameworkTwoHttpClientSocket = new \Zend\Http\Client(); $zendFrameworkTwoHttpClientSocket->setAdapter(new \Zend\Http\Client\Adapter\Socket()); $zendFrameworkTwoHttpClientProxy = new \Zend\Http\Client(); $zendFrameworkTwoHttpClientProxy->setAdapter(new \Zend\Http\Client\Adapter\Proxy()); $artaxClient = new \Amp\Artax\Client(); $transports = array(new fXmlRpc\Transport\StreamSocketTransport(), new fXmlRpc\Transport\BuzzBrowserBridge($browserSocket), new fXmlRpc\Transport\ZendFrameworkOneHttpClientBridge($zendFrameworkOneHttpClientSocket), new fXmlRpc\Transport\ZendFrameworkOneHttpClientBridge($zendFrameworkOneHttpClientProxy), new fXmlRpc\Transport\ZendFrameworkTwoHttpClientBridge($zendFrameworkTwoHttpClientSocket), new fXmlRpc\Transport\ZendFrameworkTwoHttpClientBridge($zendFrameworkTwoHttpClientProxy), new fXmlRpc\Transport\ArtaxBrowserBridge($artaxClient)); if (extension_loaded('curl') && !in_array('php_curl', $this->disabledExtensions)) { $browserCurl = new \Buzz\Browser(); $browserCurl->setClient(new \Buzz\Client\Curl()); $transports[] = new fXmlRpc\Transport\BuzzBrowserBridge($browserCurl); $zendFrameworkOneHttpClientCurl = new \Zend_Http_Client(); $zendFrameworkOneHttpClientCurl->setAdapter(new \Zend_Http_Client_Adapter_Curl()); $transports[] = new fXmlRpc\Transport\ZendFrameworkOneHttpClientBridge($zendFrameworkOneHttpClientCurl); $zendFrameworkTwoHttpClientCurl = new \Zend\Http\Client(); $zendFrameworkTwoHttpClientCurl->setAdapter(new \Zend\Http\Client\Adapter\Curl()); $transports[] = new fXmlRpc\Transport\ZendFrameworkTwoHttpClientBridge($zendFrameworkTwoHttpClientCurl); $guzzle = new \Guzzle\Http\Client(); $transports[] = new fXmlRpc\Transport\GuzzleBridge($guzzle); $transports[] = new fXmlRpc\Transport\CurlTransport(); } return $transports; }
/** * HumHub API * * @param string $action * @param array $params * @return array */ public static function request($action, $params = []) { if (!Yii::$app->params['humhub']['apiEnabled']) { return []; } $url = Yii::$app->params['humhub']['apiUrl'] . '/' . $action; $params['version'] = urlencode(Yii::$app->version); $params['installId'] = Setting::Get('installationId', 'admin'); $url .= '?'; foreach ($params as $name => $value) { $url .= urlencode($name) . '=' . urlencode($value) . "&"; } try { $http = new \Zend\Http\Client($url, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => CURLHelper::getOptions(), 'timeout' => 30)); $response = $http->send(); $json = $response->getBody(); } catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $ex) { Yii::error('Could not connect to HumHub API! ' . $ex->getMessage()); return []; } catch (Exception $ex) { Yii::error('Could not get HumHub API response! ' . $ex->getMessage()); return []; } try { return Json::decode($json); } catch (\yii\base\InvalidParamException $ex) { Yii::error('Could not parse HumHub API response! ' . $ex->getMessage()); return []; } }
public function __construct($apiKey) { $this->setApiKey($apiKey); $client = new \Zend\Http\Client(); $client->setOptions(array('strictredirects' => true, 'adapter' => 'Zend\\Http\\Client\\Adapter\\Curl')); $this->setHttpClient($client); }
public static function send() { $me = new self("global"); $sent = array(); $pastlink = new FutureLink_PastUI(); $feed = $pastlink->feed(); $items = array(); //we send something only if we have something to send if (empty($feed->feed->entry) == false) { foreach ($feed->feed->entry as &$item) { if (empty($item->futurelink->href) || isset($sent[$item->futurelink->hash])) { continue; } $sent[$item->futurelink->hash] = true; $client = new Zend\Http\Client($item->futurelink->href, array('timeout' => 60)); if (!empty($feed->feed->entry)) { $client->setParameterPost(array('protocol' => 'futurelink', 'metadata' => json_encode($feed))); try { $client->setMethod(Zend\Http\Request::METHOD_POST); $response = $client->send(); $request = $client->getLastResponse(); $result = $response->getBody(); $resultJson = json_decode($response->getBody()); //Here we add the date last updated so that we don't have to send it if not needed, saving load time. if (!empty($resultJson->feed) && $resultJson->feed == "success") { $me->addItem(array('dateLastUpdated' => $item->pastlink->dateLastUpdated, 'pastlinklinkHash' => $item->pastlink->hash, 'futurelinkHash' => $item->futurelink->hash)); } $items[$item->pastlink->text] = $result; } catch (Exception $e) { } } } return $items; } }
/** * Returns page XML/JSON content from remote web as array * * CURLOPT_HEADER - Include header in result? (0 = yes, 1 = no) * CURLOPT_RETURNTRANSFER - (true = return, false = print) data * * @param string $url "http://domain.tld" * @param array $params GET params * @throws \Exception when cURL us not installed * @throws \Exception when Json cannot be decoded * or the encoded data is deeper than the recursion limit. * @throws \Exception when response body contains error element * @throws \Exception when reponse status code is not 200 * @throws \Exception when content is not JSON neither XML * @return array */ public function getRequestDataResponseAsArray($url, array $params) { $url = $this->buildQuery($url, $params); if (!function_exists('curl_init')) { throw new \Exception('cURL is not installed!'); } $curlAdapterConfig = array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true, CURLOPT_USERAGENT => "Mozilla/5.0", CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYHOST => $this->trustSSLHost ? 0 : 2, CURLOPT_SSL_VERIFYPEER => $this->trustSSLHost ? 0 : 1)); $client = new \Zend\Http\Client($url, $curlAdapterConfig); $response = $client->send(); // Response head error handling $responseStatusCode = $response->getStatusCode(); if ($responseStatusCode !== 200) { throw new \Exception("Response status code: " . $responseStatusCode); } // $output = $response->getBody(); $dataArray = array(); if ($this->isJson($output)) { $dataArray = \Zend\Json\Json::decode($output, \Zend\Json\Json::TYPE_ARRAY); if ($dataArray === NULL) { throw new \Exception('Json cannot be decoded or the encoded data is deeper than the recursion limit.'); } } elseif ($this->isXml($output)) { $xml = simplexml_load_string($output, "SimpleXMLElement", LIBXML_NOCDATA); $json = \Zend\Json\Json::encode($xml); $dataArray = \Zend\Json\Json::decode($json, \Zend\Json\Json::TYPE_ARRAY); } else { throw new \Exception('Content is not JSON neither XML'); } return $dataArray; }
/** * Returns request handler * * @return \Zend\Http\Client */ public function getRequestHandler() { if (!isset($this->requestHandler)) { $requestHandler = new \Zend\Http\Client(); $requestHandler->setOptions(array('timeout' => 60)); $this->setRequestHandler($requestHandler); } return $this->requestHandler; }
public function getServiceConfig() { return array('factories' => array('Wechat\\Model\\Wechat' => function (ServiceManager $sm) { $config = $sm->get('config'); $client = new \Zend\Http\Client(); $client->setAdapter(new \Zend\Http\Client\Adapter\Curl()); // $redis = $sm->get('Wechat\Redis\Wechat'); return new \Wechat\Model\Wechat($config['wechat'], $client); })); }
public function sendPushNotification(PushNotification $notification) { $app = $this->getSetting('App'); $devices = array_filter(explode(',', $this->getSetting('Devices')), 'strlen'); if (!$app) { throw new PushException('No application was selected.'); } if (!isset(self::$applications[$app])) { throw new PushException(sprintf('No settings were provided for application "%s"', $app)); } if (!$devices) { throw new PushException('At least one device type must be selected to send to.'); } $user = self::$applications[$app]['key']; $pass = self::$applications[$app]['secret']; $request = function ($url, $payload) use($user, $pass) { $client = new Zend\Http\Client($url); $client->setAuth($user, $pass); $client->setHeaders('Content-Type: application/json'); $client->setRawData(json_encode($payload), 'application/json'); try { $response = $client->request('POST'); } catch (Zend\Http\Client_Exception $e) { throw new PushException($e->getMessage(), $e->getCode(), $e); } if ($response->isError()) { throw new PushException($response->getBody(), $response->getStatus()); } }; // Use the V1 API for sending to Android, Blackberry and iOS. if (array_intersect($devices, array(self::ANDROID, self::BLACKBERRY, self::IOS))) { $body = array(); if (in_array(self::ANDROID, $devices)) { $body['android'] = array('alert' => $notification->Content); } if (in_array(self::BLACKBERRY, $devices)) { $body['blackberry'] = array('content-type' => 'text/plain', 'body' => $notification->Content); } if (in_array(self::IOS, $devices)) { $body['aps'] = array('badge' => $this->getSetting('Badge') == 'inc' ? '+1' : $this->getSetting('Badge'), 'alert' => $notification->Content, 'sound' => $this->getSetting('Sound')); } $request(self::V1_API_URL . '/broadcast/', $body); } // Use the V2 API for sending to Windows. if (array_intersect($devices, array(self::MPNS, self::WNS))) { $types = array(); if (in_array(self::MPNS, $devices)) { $types[] = 'mpns'; } if (in_array(self::WNS, $devices)) { $types[] = 'wns'; } $request(self::V2_API_URL . '/broadcast/', array('notification' => array('alert' => $notification->Content), 'device_types' => $types)); } }
/** * Installs latest compatible module version * * @param type $moduleId */ public function install($moduleId) { $modulePath = Yii::getAlias(Yii::$app->params['moduleMarketplacePath']); if (!is_writable($modulePath)) { throw new HttpException(500, Yii::t('AdminModule.libs_OnlineModuleManager', 'Module directory %modulePath% is not writeable!', array('%modulePath%' => $modulePath))); } $moduleInfo = $this->getModuleInfo($moduleId); if (!isset($moduleInfo['latestCompatibleVersion'])) { throw new Exception(Yii::t('AdminModule.libs_OnlineModuleManager', "No compatible module version found!")); } $moduleDir = $modulePath . DIRECTORY_SEPARATOR . $moduleId; if (is_dir($moduleDir)) { $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($moduleDir, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST); foreach ($files as $fileinfo) { $todo = $fileinfo->isDir() ? 'rmdir' : 'unlink'; $todo($fileinfo->getRealPath()); } rmdir($moduleDir); #throw new HttpException(500, Yii::t('AdminModule.libs_OnlineModuleManager', 'Module directory for module %moduleId% already exists!', array('%moduleId%' => $moduleId))); } // Check Module Folder exists $moduleDownloadFolder = Yii::getAlias("@runtime/module_downloads"); if (!is_dir($moduleDownloadFolder)) { if (!@mkdir($moduleDownloadFolder)) { throw new Exception("Could not create module download folder!"); } } $version = $moduleInfo['latestCompatibleVersion']; // Download $downloadUrl = $version['downloadUrl']; $downloadTargetFileName = $moduleDownloadFolder . DIRECTORY_SEPARATOR . basename($downloadUrl); try { $http = new \Zend\Http\Client($downloadUrl, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => CURLHelper::getOptions(), 'timeout' => 30)); $response = $http->send(); file_put_contents($downloadTargetFileName, $response->getBody()); } catch (Exception $ex) { throw new HttpException('500', Yii::t('AdminModule.libs_OnlineModuleManager', 'Module download failed! (%error%)', array('%error%' => $ex->getMessage()))); } // Extract Package if (file_exists($downloadTargetFileName)) { $zip = new ZipArchive(); $res = $zip->open($downloadTargetFileName); if ($res === TRUE) { $zip->extractTo($modulePath); $zip->close(); } else { throw new HttpException('500', Yii::t('AdminModule.libs_OnlineModuleManager', 'Could not extract module!')); } } else { throw new HttpException('500', Yii::t('AdminModule.libs_OnlineModuleManager', 'Download of module failed!')); } Yii::$app->moduleManager->flushCache(); Yii::$app->moduleManager->register($modulePath . DIRECTORY_SEPARATOR . $moduleId); }
/** * @param IL10N $l10n * @param IConfig $config * @param IClientService $clientService */ public function __construct(IL10N $l10n, IConfig $config, IClientService $clientService) { parent::__construct($l10n, $config, $clientService); $this->scriptLocation = __DIR__ . '/../../scripts/pagekite/pagekite.py'; // TODO: DI $this->xmlRpcClient = new \Zend\XmlRpc\Client($this->rpcUrl); $client = new \Zend\Http\Client(); $client->setAdapter('Zend\\Http\\Client\\Adapter\\Proxy'); $client->setOptions(['sslcafile' => \OC::$SERVERROOT . '/config/ca-bundle.crt']); $this->xmlRpcClient->setHttpClient($client); }
function getJsonObject($channelId) { $client = new Zend\Http\Client(); $url = sprintf('http://api.thingspeak.com/channels/%d/feed.json', $channelId); $client->setUri($url)->setMethod(\Zend\Http\Request::METHOD_GET); $response = $client->send(); $responseObject = \Zend\Json\Json::decode($response->getBody()); if (-1 === $responseObject) { exit(sprintf('Nothing found under %s' . PHP_EOL, $url)); } return $responseObject; }
private function getTimeStamp() { //May be used soon for encrypting futurelinks if (isset($_REQUEST['action'], $_REQUEST['hash']) && $_REQUEST['action'] == 'timestamp') { $client = new Zend\Http\Client(TikiLib::tikiUrl() . 'tiki-timestamp.php', array('timeout' => 60)); $client->getRequest()->getQuery()->set('hash', $_REQUEST['hash']); $client->getRequest()->getQuery()->set('clienttime', time()); $response = $client->send(); echo $response->getBody(); exit; } }
/** * {@inheritDoc} * @see \Zend\ServiceManager\Factory\FactoryInterface::__invoke() */ public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { $config = $container->get('config'); $clientConfig = $config['hermes']; $client = new \Zend\Http\Client($clientConfig['uri'], $clientConfig['http_client']['options']); $client->getRequest()->getHeaders()->addHeaders($clientConfig['headers']); $hermes = new Client($client, isset($clientConfig['service_name']) ? $clientConfig['service_name'] : null, $clientConfig['depth']); if (isset($clientConfig['append_path'])) { $hermes->setAppendPath($clientConfig['append_path']); } return $hermes; }
/** * @param string $par Query Parameter * @param string $geoCoderUrl Url of the geo location service * @param string $land language * * @return array|mixed|string */ public function __invoke($par, $geoCoderUrl, $land) { $client = new \Zend\Http\Client($geoCoderUrl); $client->setMethod('GET'); // more countries 'country' => 'DE,CH,AT' // with countryCode 'zoom' => 2 $plz = 0 < (int) $par ? 1 : 0; $client->setParameterGet(array('q' => $par, 'country' => 'DE', 'plz' => $plz, 'zoom' => 1)); $response = $client->send(); $result = $response->getBody(); $result = json_decode($result); $result = (array) $result->result; return $result; }
/** * This method call Bit.ly to shorten a given URL. * @param unknown_type $url * @return unknown */ public function shortenUrl($url) { if ($this->getOptions()->getBitlyApiKey() && $this->getOptions()->getBitlyUsername()) { $client = new \Zend\Http\Client($this->getOptions()->getBitlyUrl()); $client->setParameterGet(array('format' => 'json', 'longUrl' => $url, 'login' => $this->getOptions()->getBitlyUsername(), 'apiKey' => $this->getOptions()->getBitlyApiKey())); $result = $client->send(); if ($result) { $jsonResult = \Zend\Json\Json::decode($result->getBody()); if ($jsonResult->status_code == 200) { return $jsonResult->data->url; } } } return $url; }
/** * @param null $id * @param array $queryParams * @return mixed */ protected function requestGet($id = null, $queryParams = array()) { $uri = $this->getApiPath(); if (!empty($id)) { $uri .= '/' . $id; } if (!empty($queryParams)) { $uri .= '?' . http_build_query($queryParams); } $request = new Request(); $request->setMethod(Request::METHOD_GET); $request->setUri($uri); $request->getHeaders()->addHeaders(array('Accept' => 'application/json', 'Authorization' => $this->getTokenType() . ' ' . $this->getAccessToken())); $client = new \Zend\Http\Client(null, array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false))); return $client->send($request); }
/** * @param Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { $clientIP = "115.78.167.37"; // $clientIP = $this->_request->getClientIp(); $httpClient = new \Zend\Http\Client(); $uri = 'http://freegeoip.net/json/' . $clientIP; $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = \Zend\Json\Decoder::decode($httpClient->send()->getBody()); $this->_customerSession->setLocationData($response); $this->_customerSession->setLocated(true); } catch (\Exception $e) { $this->_logger->critical($e); } return $this; }
public function __invoke($par) { $config = $this->getController()->getServiceLocator()->get('config'); if (empty($config['geocoder_cross_url'])) { throw new \InvalidArgumentException('Now Service-Adress for Geo-Service available'); } $client = new \Zend\Http\Client($config['geocoder_photon_url']); $client->setMethod('GET'); // more countries 'country' => 'DE,CH,AT' // with countryCode 'zoom' => 2 $plz = 0 < (int) $par ? 1 : 0; $client->setParameterGet(array('q' => $par, 'country' => 'DE', 'plz' => $plz, 'zoom' => 1)); $response = $client->send(); $result = $response->getBody(); $result = json_decode($result); $result = (array) $result->result; return $result; }
public static function sendRequest($url, $postString = '', $method = \Zend\Http\Request::METHOD_POST) { $client = new \Zend\Http\Client(); $client->setAdapter(new \Zend\Http\Client\Adapter\Curl()); $request = new \Zend\Http\Request(); $request->setUri($url); $request->setMethod($method); if (is_array($postString)) { $params = $postString; $postString = ''; foreach ($params as $key => $value) { $postString .= $key . '=' . urlencode($value) . '&'; } $postString = substr($postString, 0, strlen($postString) - 1); } $request->setContent($postString); $response = $client->dispatch($request); return $response->getContent(); }
/** * Downloads the update package * * @throws Exception */ public function download() { $targetFile = Yii::$app->getModule('updater')->getTempPath() . DIRECTORY_SEPARATOR . $this->fileName; // Unlink download if exists and not matches the md5 if (is_file($targetFile) && md5_file($targetFile) != $this->md5) { unlink($targetFile); } // Download Package if (!is_file($targetFile)) { try { $http = new \Zend\Http\Client($this->downloadUrl, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => Yii::$app->getModule('updater')->getCurlOptions(), 'timeout' => 300)); $response = $http->send(); file_put_contents($targetFile, $response->getBody()); } catch (Exception $ex) { throw new Exception(Yii::t('UpdaterModule.libs_UpdatePackage', 'Update download failed! (%error%)', array('%error%' => $ex->getMessage()))); } } if (md5_file($targetFile) != $this->md5) { throw new Exception(Yii::t('UpdaterModule.base', 'Update package invalid!')); } }
{ return in_array(strtolower($needle), array_map('strtolower', $haystack)); } /** Please send me: array( 'uri'=> '', 'method'=>''[, 'curloptions'=> array( ... ) ]) I will throw an Exception if something goes wrong so no need to validate But you can decide whether you wnat me to do it or not */ public static function sendRequest($arrayParms, $throwEx = true) { Utils::arrayKeyExists(array('url', 'method'), $arrayParms); $client = new \Zend\Http\Client($arrayParms['url']); $client->setMethod($arrayParms['method']); switch ($arrayParms['method']) { case POST: Utils::arrayKeyExists('payload', $arrayParms); $client->setParameterPost($arrayParms['payload']); break; case GET: Utils::arrayKeyExists('payload', $arrayParms); $client->setParameterGet($arrayParms['payload']); break; } $adapter = new \Zend\Http\Client\Adapter\Curl(); $curloptions = array(CURLOPT_POST => 1, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_SSL_VERIFYHOST => FALSE); if (array_key_exists('curloptions', $arrayParms)) { $curloptions = array_merge($curloptions, $arrayParms['curloptions']); } $adapter->setOptions(array('curloptions' => $curloptions)); $client->setAdapter($adapter); $response = $client->send(); if ($response->isSuccess()) {
/** * Returns all available updates for a given version * * @param type $version */ public static function getAvailableUpdate() { $info = []; if (class_exists('\\humhub\\modules\\admin\\libs\\HumHubAPI')) { $info = \humhub\modules\admin\libs\HumHubAPI::request('v1/modules/getHumHubUpdates', ['updaterVersion' => Yii::$app->getModule('updater')->version]); } else { // older Versions try { $url = Yii::$app->getModule('admin')->marketplaceApiUrl . "getHumHubUpdates?version=" . Yii::$app->version . "&updaterVersion=" . Yii::$app->getModule('updater')->version . "&installId=" . Setting::Get('installationId', 'admin'); $http = new \Zend\Http\Client($url, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => Yii::$app->getModule('updater')->getCurlOptions(), 'timeout' => 30)); $response = $http->send(); $info = Json::decode($response->getBody()); } catch (Exception $ex) { throw new Exception(Yii::t('UpdaterModule.base', 'Could not get update info online! (%error%)', array('%error%' => $ex->getMessage()))); } } if (!isset($info['fromVersion'])) { return null; } $package = new UpdatePackage($info['fileName'], $info['fromVersion'], $info['toVersion']); $package->md5 = $info['md5']; $package->downloadUrl = $info['downloadUrl']; return $package; }
public function getCausas() { $cliente = new \Zend\Http\Client('http://civil.poderjudicial.cl', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true)); $headers = $cliente->getRequest()->getHeaders(); $cookies = new Zend\Http\Cookies($headers); $cliente->setMethod('GET'); $response = $cliente->send(); $cliente->setUri('http://civil.poderjudicial.cl/CIVILPORWEB/AtPublicoViewAccion.do?tipoMenuATP=1'); $cookies->addCookiesFromResponse($response, $cliente->getUri()); $response = $cliente->send(); echo '<pre>'; print_r($response); echo '</pre>'; }
/** * Sends a request and returns a response * * @param CartRecover_Request $request * @return Cart_Recover_Response */ public function sendRequest(CartRecover_Request $request) { $this->client->setUri($request->getUri()); $this->client->setParameterGet($request->getParams()); $this->client->setMethod($request->getMethod()); $this->client->setHeaders(array('Accept' => 'application/json')); $this->response = $this->client->send(); if ($this->response->getHeaders()->get('Content-Type')->getFieldValue() != 'application/json') { throw new CartRecover_Exception_UnexpectedValueException("Unknown response format."); } $body = json_decode($this->response->getContent(), true); $response = new CartRecover_Response(); $response->setRawResponse($this->response->toString()); $response->setBody($body); $response->setHeaders($this->response->getHeaders()->toArray()); $response->setStatus($this->response->getReasonPhrase(), $this->response->getStatusCode()); return $response; }
/** * Get a loader object to test. * * @param array $config Configuration * @param \VuFind\Content\Covers\PluginManager $manager Plugin manager (null to create mock) * @param ThemeInfo $theme Theme info object (null to create default) * @param \Zend\Http\Client $client HTTP client (null to create TestAdapter) * @param array|bool $mock Array of functions to mock, or false for real object * * @return void */ protected function getLoader($config = [], $manager = null, $theme = null, $client = null, $mock = false) { $config = new Config($config); if (null === $manager) { $manager = $this->getMock('VuFind\\Content\\Covers\\PluginManager'); } if (null === $theme) { $theme = new ThemeInfo($this->getThemeDir(), $this->testTheme); } if (null === $client) { $adapter = new TestAdapter(); $client = new \Zend\Http\Client(); $client->setAdapter($adapter); } if ($mock) { return $this->getMock('VuFind\\Cover\\Loader', $mock, [$config, $manager, $theme, $client]); } return new Loader($config, $manager, $theme, $client); }
/** * Test no proxify with local address. * * @return void */ public function testNoProxifyLocal() { $service = new Service(array('proxy_host' => 'localhost', 'proxy_port' => '666')); foreach ($this->local as $name => $address) { $client = new \Zend\Http\Client($address); $client->setAdapter(new \Zend\Http\Client\Adapter\Test()); $client = $service->proxify($client); $this->assertInstanceOf('Zend\\Http\\Client\\Adapter\\Test', $client->getAdapter(), sprintf('Failed to proxify %s: %s', $name, $address)); } }
<?php return array('abstract_factories' => array('Minibus\\Controller\\Process\\AbstractFactory\\AbstractDataTransferFactory', 'Zend\\Cache\\Service\\StorageCacheAbstractServiceFactory', 'Zend\\Log\\LoggerAbstractServiceFactory', 'Minibus\\Model\\Browse\\Factory\\AbstractFormatterFactory'), 'factories' => array('entitymanager' => 'DoctrineORMModule\\Service\\EntityManagerFactory', 'Minibus\\Model\\Io\\Rest\\Client' => function ($serviceManager) { $httpClient = $serviceManager->get('HttpClient'); $enableRestClientSslVerification = false; $httpRestJsonClient = new Minibus\Model\Io\Rest\Client($httpClient, $enableRestClientSslVerification); return $httpRestJsonClient; }, 'HttpClient' => function ($serviceManager) { $httpClient = new Zend\Http\Client(); $httpClient->setAdapter('Zend\\Http\\Client\\Adapter\\Curl'); return $httpClient; }), 'invokables' => array('configuration-handler' => 'Minibus\\Model\\Configuration\\Service\\ConfigurationHandler', 'process-state-handler' => 'Minibus\\Model\\Process\\Service\\ProcessStateHandler', 'log-handler' => 'Minibus\\Controller\\Log\\Service\\LogHandler', 'alert-handler' => 'Minibus\\Controller\\Alert\\Service\\AlertHandler', 'alert-data-handler' => 'Minibus\\Controller\\Alert\\Service\\AlertDataHandler', 'endpoint-connection-builder' => 'Minibus\\Controller\\Process\\Service\\Connection\\EndpointConnectionBuilder', 'process-updater' => 'Minibus\\Model\\Process\\Service\\ProcessUpdater', 'process-execution-handler' => 'Minibus\\Controller\\Process\\Service\\ProcessExecutionHandler', 'process-sheduler' => 'Minibus\\Controller\\Process\\Service\\Sheduler', 'datatypes-handler' => 'Minibus\\Model\\Configuration\\Service\\DataTypesHandler', 'hash-calculator' => 'Minibus\\Model\\Process\\Service\\Hash\\HashCalculator', 'zfc-user-redirection' => 'Minibus\\Controller\\Auth\\Service\\ZfcUserRedirectionListener', 'file-auth-service' => 'Minibus\\Controller\\Auth\\Service\\FileAuthService', 'scp_client' => 'Minibus\\Model\\Io\\Scp\\ScpClient', 'pgp_decrypt' => 'Minibus\\Model\\Io\\Crypt\\PgpDecrypt', 'pgp_encrypt' => 'Minibus\\Model\\Io\\Crypt\\PgpEncrypt'), 'aliases' => array('translator' => 'MvcTranslator', 'json_rest_client' => 'Minibus\\Model\\Io\\Rest\\Client'));
/** * Performs HTTP request to given $url using given HTTP $method. * Send additinal query specified by variable/value array, * On success returns HTTP response without headers, false on failure. * * @param string $url OpenID server url * @param string $method HTTP request method 'GET' or 'POST' * @param array $params additional qwery parameters to be passed with * @param int &$staus HTTP status code * request * @return mixed */ protected function _httpRequest($url, $method = 'GET', array $params = array(), &$status = null) { $client = $this->_httpClient; if ($client === null) { $client = new \Zend\Http\Client($url, array('maxredirects' => 4, 'timeout' => 15, 'useragent' => 'Zend_OpenId')); } else { $client->setUri($url); } $client->resetParameters(); if ($method == 'POST') { $client->setMethod(\Zend\Http\Client::POST); $client->setParameterPost($params); } else { $client->setMethod(\Zend\Http\Client::GET); $client->setParameterGet($params); } try { $response = $client->request(); } catch (\Exception $e) { $this->_setError('HTTP Request failed: ' . $e->getMessage()); return false; } $status = $response->getStatus(); $body = $response->getBody(); if ($status == 200 || $status == 400 && !empty($body)) { return $body; } else { $this->_setError('Bad HTTP response'); return false; } }