本文整理汇总了PHP中JHttpFactory类的典型用法代码示例。如果您正苦于以下问题:PHP JHttpFactory类的具体用法?PHP JHttpFactory怎么用?PHP JHttpFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JHttpFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: downloadPackage
/**
* Downloads a package
*
* @param string $url URL of file to download
* @param string $target Download target filename [optional]
*
* @return mixed Path to downloaded package or boolean false on failure
*
* @since 11.1
*/
public static function downloadPackage($url, $target = false)
{
$config = JFactory::getConfig();
// Capture PHP errors
$track_errors = ini_get('track_errors');
ini_set('track_errors', true);
// Set user agent
$version = new JVersion();
ini_set('user_agent', $version->getUserAgent('Installer'));
$http = JHttpFactory::getHttp();
$response = $http->get($url);
if (200 != $response->code) {
JLog::add(JText::_('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT'), JLog::WARNING, 'jerror');
return false;
}
if ($response->headers['wrapper_data']['Content-Disposition']) {
$contentfilename = explode("\"", $response->headers['wrapper_data']['Content-Disposition']);
$target = $contentfilename[1];
}
// Set the target path if not given
if (!$target) {
$target = $config->get('tmp_path') . '/' . self::getFilenameFromURL($url);
} else {
$target = $config->get('tmp_path') . '/' . basename($target);
}
// Write buffer to file
JFile::write($target, $response->body);
// Restore error tracking to what it was before
ini_set('track_errors', $track_errors);
// Bump the max execution time because not using built in php zip libs are slow
@set_time_limit(ini_get('max_execution_time'));
// Return the name of the downloaded package
return basename($target);
}
示例2: get
/**
* Request a page and return it as string.
*
* @param string $url A url to request.
* @param string $method Request method, GET or POST.
* @param string $query Query string. eg: 'option=com_content&id=11&Itemid=125'. <br /> Only use for POST.
* @param array $option An option array to override CURL OPT.
*
* @throws \Exception
* @return mixed If success, return string, or return false.
*/
public static function get($url, $method = 'get', $query = '', $option = array())
{
if ((!function_exists('curl_init') || !is_callable('curl_init')) && ini_get('allow_url_fopen')) {
$return = new Object();
$return->body = file_get_contents($url);
return $return;
}
$options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1", CURLOPT_FOLLOWLOCATION => !ini_get('open_basedir') ? true : false, CURLOPT_SSL_VERIFYPEER => false);
// Merge option
$options = $option + $options;
$http = \JHttpFactory::getHttp(new \JRegistry($options), 'curl');
try {
switch ($method) {
case 'post':
case 'put':
case 'patch':
$result = $http->{$method}(UriHelper::safe($url), $query);
break;
default:
$result = $http->{$method}(UriHelper::safe($url));
break;
}
} catch (\Exception $e) {
return new NullObject();
}
return $result;
}
示例3: getBalance
private function getBalance()
{
$cache = JFactory::getCache('paypal', 'output');
$cache->setCaching(1);
$cache->setLifeTime($this->params->get('cache', 60) * 60);
$key = md5($this->params->toString());
if (!($result = $cache->get($key))) {
try {
$http = JHttpFactory::getHttp();
$data = array('USER' => $this->params->get('apiuser'), 'PWD' => $this->params->get('apipw'), 'SIGNATURE' => $this->params->get('apisig'), 'VERSION' => '112', 'METHOD' => 'GetBalance');
$result = $http->post($this->url, $data);
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage($e->getMessage());
return $this->output = JText::_('ERROR');
}
$cache->store($result, $key);
}
if ($result->code != 200) {
$msg = __CLASS__ . ' HTTP-Status ' . JHtml::_('link', 'http://wikipedia.org/wiki/List_of_HTTP_status_codes#' . $result->code, $result->code, array('target' => '_blank'));
JFactory::getApplication()->enqueueMessage($msg, 'error');
return $this->output = JText::_('ERROR');
}
parse_str($result->body, $result->body);
if (!isset($result->body['ACK']) || $result->body['ACK'] != 'Success') {
return $this->output = $result->body['L_SHORTMESSAGE0'];
}
$this->success = true;
$this->output = $result->body['L_AMT0'] . ' ' . $result->body['L_CURRENCYCODE0'];
}
示例4: getFeed
/**
* Method to load a URI into the feed reader for parsing.
*
* @param string $uri The URI of the feed to load. Idn uris must be passed already converted to punycode.
*
* @return JFeedReader
*
* @since 12.3
* @throws InvalidArgumentException
* @throws RuntimeException
*/
public function getFeed($uri)
{
// Create the XMLReader object.
$reader = new XMLReader();
// Open the URI within the stream reader.
if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
// Retry with JHttpFactory that allow using CURL and Sockets as alternative method when available
// Adding a valid user agent string, otherwise some feed-servers returning an error
$options = new \joomla\Registry\Registry();
$options->set('userAgent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0');
$connector = JHttpFactory::getHttp($options);
$feed = $connector->get($uri);
if ($feed->code != 200) {
throw new RuntimeException('Unable to open the feed.');
}
// Set the value to the XMLReader parser
if (!$reader->xml($feed->body, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
throw new RuntimeException('Unable to parse the feed.');
}
}
try {
// Skip ahead to the root node.
while ($reader->read()) {
if ($reader->nodeType == XMLReader::ELEMENT) {
break;
}
}
} catch (Exception $e) {
throw new RuntimeException('Error reading feed.', $e->getCode(), $e);
}
// Setup the appopriate feed parser for the feed.
$parser = $this->_fetchFeedParser($reader->name, $reader);
return $parser->parse();
}
示例5: send
/**
* Looks for an update to the extension
*
* @return string
*/
public function send()
{
JSession::checkToken('get') or jexit(JText::_('JINVALID_TOKEN'));
$statsModel = $this->getModel();
$data = $statsModel->getData();
// Set up our JRegistry object for the BDHttp connector
$options = new JRegistry();
// Use a 30 second timeout
$options->set('timeout', 30);
try {
$transport = JHttpFactory::getHttp($options);
} catch (Exception $e) {
echo '###Something went wrong! We could not even get a transporter!###';
JFactory::getApplication()->close();
}
// We have to provide the user-agent here, because Joomla! 2.5 won't understand it
// If we add it in the $options...
$request = $transport->post('https://stats.compojoom.com', $data, array('user-agent' => 'LibCompojoom/4.0'));
// There is a bug in curl, that we don't have an work-around in j2.5 That's why we
// will asume here that 100 == 200...
if ($request->code == 200 || JVERSION < 3 && $request->code == 100) {
// Let's update the date
$statsModel->dataGathered();
echo '###All Good!###';
} else {
echo '###Something went wrong!###';
}
// Cut the execution short
JFactory::getApplication()->close();
}
示例6: getFeed
/**
* Method to load a URI into the feed reader for parsing.
*
* @param string $uri The URI of the feed to load. Idn uris must be passed already converted to punycode.
*
* @return JFeedReader
*
* @since 12.3
* @throws InvalidArgumentException
* @throws RuntimeException
*/
public function getFeed($uri)
{
// Create the XMLReader object.
$reader = new XMLReader();
// Open the URI within the stream reader.
if (!@$reader->open($uri, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
// If allow_url_fopen is enabled
if (ini_get('allow_url_fopen')) {
// This is an error
throw new RuntimeException('Unable to open the feed.');
} else {
// Retry with JHttpFactory that allow using CURL and Sockets as alternative method when available
$connector = JHttpFactory::getHttp();
$feed = $connector->get($uri);
// Set the value to the XMLReader parser
if (!$reader->xml($feed->body, null, LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_NOWARNING)) {
throw new RuntimeException('Unable to parse the feed.');
}
}
}
try {
// Skip ahead to the root node.
while ($reader->read()) {
if ($reader->nodeType == XMLReader::ELEMENT) {
break;
}
}
} catch (Exception $e) {
throw new RuntimeException('Error reading feed.');
}
// Setup the appopriate feed parser for the feed.
$parser = $this->_fetchFeedParser($reader->name, $reader);
return $parser->parse();
}
示例7: __construct
/**
* Constructor.
*
* @param JRegistry $options OAuth1Client options object.
* @param JHttp $client The HTTP client object.
* @param JInput $input The input object
* @param JApplicationWeb $application The application object
* @param string $version Specify the OAuth version. By default we are using 1.0a.
*
* @since 13.1
*/
public function __construct(JRegistry $options = null, JHttp $client = null, JInput $input = null, JApplicationWeb $application = null, $version = null)
{
$this->options = isset($options) ? $options : new JRegistry();
$this->client = isset($client) ? $client : JHttpFactory::getHttp($this->options);
$this->input = isset($input) ? $input : JFactory::getApplication()->input;
$this->application = isset($application) ? $application : new JApplicationWeb();
$this->version = isset($version) ? $version : '1.0a';
}
示例8: getContents
public function getContents($url, $fopen = 0)
{
$hash = md5('getByUrl_' . $url . '_' . $fopen);
if (NNCache::has($hash)) {
return NNCache::get($hash);
}
return NNCache::set($hash, JHttpFactory::getHttp()->get($url)->body);
}
示例9: __construct
/**
*
*/
public function __construct()
{
jimport('joomla.http.factory');
if (!class_exists('JHttpFactory')) {
throw new BadFunctionCallException(JchPlatformUtility::translate('JHttpFactory not present. Please upgrade your version of Joomla. Exiting plugin...'));
}
$aOptions = array('follow_location' => true);
$oOptions = new JRegistry($aOptions);
$this->oHttpAdapter = JHttpFactory::getAvailableDriver($oOptions);
}
示例10: downloadPackage
/**
* Downloads a package
*
* @param string $url URL of file to download
* @param string $target Download target filename [optional]
*
* @return mixed Path to downloaded package or boolean false on failure
*
* @since 11.1
*/
public static function downloadPackage($url, $target = false)
{
$config = JFactory::getConfig();
// Capture PHP errors
$php_errormsg = 'Error Unknown';
$track_errors = ini_get('track_errors');
ini_set('track_errors', true);
// Set user agent
$version = new JVersion();
ini_set('user_agent', $version->getUserAgent('Installer'));
$http = JHttpFactory::getHttp();
// load installer plugins, and allow url and headers modification
$headers = array();
JPluginHelper::importPlugin('installer');
$dispatcher = JDispatcher::getInstance();
$results = $dispatcher->trigger('onInstallerBeforePackageDownload', array(&$url, &$headers));
try {
$response = $http->get($url, $headers);
} catch (Exception $exc) {
$response = null;
}
if (is_null($response)) {
JError::raiseWarning(42, JText::_('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT'));
return false;
}
if (302 == $response->code && isset($response->headers['Location'])) {
return self::downloadPackage($response->headers['Location']);
} elseif (200 != $response->code) {
if ($response->body === '') {
$response->body = $php_errormsg;
}
JError::raiseWarning(42, JText::sprintf('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT', $response->body));
return false;
}
// Parse the Content-Disposition header to get the file name
if (isset($response->headers['Content-Disposition']) && preg_match("/\\s*filename\\s?=\\s?(.*)/", $response->headers['Content-Disposition'], $parts)) {
$target = trim(rtrim($parts[1], ";"), '"');
}
// Set the target path if not given
if (!$target) {
$target = $config->get('tmp_path') . '/' . self::getFilenameFromURL($url);
} else {
$target = $config->get('tmp_path') . '/' . basename($target);
}
// Write buffer to file
JFile::write($target, $response->body);
// Restore error tracking to what it was before
ini_set('track_errors', $track_errors);
// bump the max execution time because not using built in php zip libs are slow
@set_time_limit(ini_get('max_execution_time'));
// Return the name of the downloaded package
return basename($target);
}
示例11: getContents
public function getContents($url, $timeout = 20)
{
$hash = md5('getContents_' . $url);
if (NNCache::has($hash)) {
return NNCache::get($hash);
}
try {
$content = JHttpFactory::getHttp()->get($url, null, $timeout)->body;
} catch (RuntimeException $e) {
return '';
}
return NNCache::set($hash, $content);
}
示例12: requestRest
/**
* Get a single row
*
* @return step object
*/
public function requestRest($task = 'total', $table = false)
{
$http = JHttpFactory::getHttp();
$data = $this->getRestData();
// Getting the total
$data['task'] = $task;
$data['table'] = $table != false ? $table : '';
$request = $http->get($this->params->rest_hostname . '/index.php', $data);
$code = $request->code;
if ($code == 500) {
throw new Exception('COM_REDMIGRATOR_REDMIGRATOR_ERROR_REST_REQUEST');
} else {
return $code == 200 || $code == 301 ? $request->body : $code;
}
}
示例13: _closureCompiler
/**
* @param $code
* @return string
* @throws Exception
*/
private function _closureCompiler($code)
{
if (JString::strlen($code) > 200000) {
return $code;
}
if (!class_exists('JHttpFactory')) {
return $code;
}
$response = JHttpFactory::getHttp()->post($this->_url, array('js_code' => $code, 'output_info' => 'compiled_code', 'output_format' => 'text', 'compilation_level' => 'WHITESPACE_ONLY'), array('Content-type' => 'application/x-www-form-urlencoded', 'Connection' => 'close'), 15);
$result = $response->body;
if (preg_match('/^Error\\(\\d\\d?\\):/', $result)) {
throw new Exception('Google JS Minify: ' . $result);
}
return $result;
}
示例14: testGet
/**
* Method to test get().
*
* @return void
*
* @covers Windwalker\Helper\CurlHelper::get
*/
public function testGet()
{
$url = 'http://example.com/';
$http = \JHttpFactory::getHttp(new \JRegistry($this->options), 'curl');
// Test with Restful Api 'GET'
$helperOutput = CurlHelper::get($url);
$jHttpOutput = $http->get($url);
$this->assertEquals($helperOutput->code, $jHttpOutput->code);
$this->assertEquals($helperOutput->body, $jHttpOutput->body);
// Test with Restful Api 'POST'
$helperOutput = CurlHelper::get($url, 'post', array('key' => 'value'), array('testHeader'));
$jHttpOutput = $http->post($url, array('key' => 'value'), array('testHeader'));
$this->assertEquals($helperOutput->code, $jHttpOutput->code);
$this->assertEquals($helperOutput->body, $jHttpOutput->body);
}
示例15: downloadPackage
/**
* Downloads a package
*
* @param string $url URL of file to download
* @param string $target Download target filename [optional]
*
* @return mixed Path to downloaded package or boolean false on failure
*
* @since 11.1
*/
public static function downloadPackage($url, $target = false)
{
$config = JFactory::getConfig();
// Capture PHP errors
$php_errormsg = 'Error Unknown';
$track_errors = ini_get('track_errors');
ini_set('track_errors', true);
// Set user agent
$version = new JVersion();
ini_set('user_agent', $version->getUserAgent('Installer'));
$http = JHttpFactory::getHttp();
try {
$response = $http->get($url);
} catch (Exception $exc) {
$response = null;
}
if (is_null($response)) {
JError::raiseWarning(42, JText::_('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT'));
return false;
}
if (302 == $response->code && isset($response->headers['Location'])) {
return self::downloadPackage($response->headers['Location']);
} elseif (200 != $response->code) {
if ($response->body === '') {
$response->body = $php_errormsg;
}
JError::raiseWarning(42, JText::sprintf('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT', $response->body));
return false;
}
if (isset($response->headers['Content-Disposition'])) {
$contentfilename = explode("\"", $response->headers['Content-Disposition']);
$target = $contentfilename[1];
}
// Set the target path if not given
if (!$target) {
$target = $config->get('tmp_path') . '/' . self::getFilenameFromURL($url);
} else {
$target = $config->get('tmp_path') . '/' . basename($target);
}
// Write buffer to file
JFile::write($target, $response->body);
// Restore error tracking to what it was before
ini_set('track_errors', $track_errors);
// bump the max execution time because not using built in php zip libs are slow
@set_time_limit(ini_get('max_execution_time'));
// Return the name of the downloaded package
return basename($target);
}