本文整理汇总了PHP中Drupal::httpClient方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::httpClient方法的具体用法?PHP Drupal::httpClient怎么用?PHP Drupal::httpClient使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal
的用法示例。
在下文中一共展示了Drupal::httpClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testStatisticsTokenReplacement
/**
* Creates a node, then tests the statistics tokens generated from it.
*/
function testStatisticsTokenReplacement()
{
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
// Create user and node.
$user = $this->drupalCreateUser(array('create page content'));
$this->drupalLogin($user);
$node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $user->id()));
// Hit the node.
$this->drupalGet('node/' . $node->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $node->id();
$post = http_build_query(array('nid' => $nid));
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
global $base_url;
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$client = \Drupal::httpClient();
$client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10));
$client->post($stats_path, array('headers' => $headers, 'body' => $post));
$statistics = statistics_get($node->id());
// Generate and test tokens.
$tests = array();
$tests['[node:total-count]'] = 1;
$tests['[node:day-count]'] = 1;
$tests['[node:last-view]'] = format_date($statistics['timestamp']);
$tests['[node:last-view:short]'] = format_date($statistics['timestamp'], 'short');
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = \Drupal::token()->replace($input, array('node' => $node), array('langcode' => $language_interface->getId()));
$this->assertEqual($output, $expected, format_string('Statistics token %token replaced.', array('%token' => $input)));
}
}
示例2: request
public function request($path, $query_array = array(), $options = array())
{
$parse_url = parse_url($path);
if (isset($parse_url['scheme']) && !empty($parse_url['scheme'])) {
$validate_url = $path;
} else {
$validate_url = API_DOMAIN . $path;
}
$method = isset($options['method']) ? strtolower($options['method']) : 'get';
$post_data = isset($options['post_data']) ? $options['post_data'] : array();
$content_type = isset($options['content_type']) ? $options['content_type'] : 'form_params';
$ssl_verify = isset($options['ssl_verify']) ? $options['ssl_verify'] : FALSE;
$httpclient_options['verify'] = $ssl_verify;
if ($method == 'post') {
$httpclient_options[$content_type] = $post_data;
}
if ($query_array !== FALSE) {
$validate_url .= '?' . LoginRadius::queryBuild(LoginRadius::authentication($query_array));
}
try {
$response = \Drupal::httpClient()->{$method}($validate_url, $httpclient_options);
$data = (string) $response->getBody();
return $data;
} catch (RequestException $e) {
throw new LoginRadiusException($e->getMessage(), $e);
} catch (ClientException $e) {
throw new LoginRadiusException($e->getMessage(), $e);
} catch (Exception $e) {
throw new LoginRadiusException($e->getMessage(), $e);
}
}
示例3: testPopularContentBlock
/**
* Tests the "popular content" block.
*/
function testPopularContentBlock()
{
// Clear the block cache to load the Statistics module's block definitions.
$this->container->get('plugin.manager.block')->clearCachedDefinitions();
// Visit a node to have something show up in the block.
$node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->blocking_user->id()));
$this->drupalGet('node/' . $node->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $node->id();
$post = http_build_query(array('nid' => $nid));
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
global $base_url;
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$client = \Drupal::httpClient();
$client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10));
$client->post($stats_path, array('headers' => $headers, 'body' => $post));
// Configure and save the block.
$this->drupalPlaceBlock('statistics_popular_block', array('label' => 'Popular content', 'top_day_num' => 3, 'top_all_num' => 3, 'top_last_num' => 3));
// Get some page and check if the block is displayed.
$this->drupalGet('user');
$this->assertText('Popular content', 'Found the popular content block.');
$this->assertText("Today's", "Found today's popular content.");
$this->assertText('All time', 'Found the all time popular content.');
$this->assertText('Last viewed', 'Found the last viewed popular content.');
$this->assertRaw(l($node->label(), 'node/' . $node->id()), 'Found link to visited node.');
}
示例4: getContent
/**
* Returns the content of the enclosre as a string.
*
* @return string|false
* The content of the referenced resource, or false if the file could not be
* read. This should be checked with an ===, since an empty string could be
* returned.
*
* @throws \RuntimeException
* Thrown if the download failed.
*
* @todo Better error handling.
*/
public function getContent()
{
$response = \Drupal::httpClient()->get($this->uri)->send();
if ($response->getStatusCode() != 200) {
$args = ['%url' => $this->uri, '@code' => $response->getStatusCode()];
throw new \RuntimeException(SafeMarkup::format('Download of %url failed with code @code.', $args));
}
return $response->getBody(TRUE);
}
示例5: submit
/**
* Submit the POST request with the specified parameters.
*
* @param RequestParameters $params
* Request parameters
*
* @return string
* Body of the reCAPTCHA response
*/
public function submit(RequestParameters $params)
{
try {
$options = ['headers' => ['Content-type' => 'application/x-www-form-urlencoded'], 'body' => $params->toQueryString()];
$response = \Drupal::httpClient()->post(self::SITE_VERIFY_URL, $options);
} catch (RequestException $exception) {
\Drupal::logger('reCAPTCHA web service')->error($exception);
}
return (string) $response->getBody();
}
示例6: setUp
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->installEntitySchema('file');
$entity_manager = \Drupal::entityManager();
$link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default'), \Drupal::moduleHandler(), \Drupal::service('config.factory'), \Drupal::service('request_stack')), new RelationLinkManager(new MemoryBackend('default'), $entity_manager, \Drupal::moduleHandler(), \Drupal::service('config.factory'), \Drupal::service('request_stack')));
// Set up the mock serializer.
$normalizers = array(new FieldItemNormalizer(), new FileEntityNormalizer($entity_manager, \Drupal::httpClient(), $link_manager, \Drupal::moduleHandler()));
$encoders = array(new JsonEncoder());
$this->serializer = new Serializer($normalizers, $encoders);
}
示例7: startBackgroundJob
/**
* Starts a background job using a new process.
*
* @param \Drupal\feeds\FeedInterface $feed
* The feed to start the job for.
* @param string $method
* Method to execute on importer; one of 'import' or 'clear'.
*
* @throws Exception $e
*
* @todo Inject these dependencies.
*/
protected function startBackgroundJob(FeedInterface $feed, $method)
{
$cid = 'feeds_feed:' . $feed->id();
$token = Crypt::randomStringHashed(55);
\Drupal::state()->set($cid, array('token' => $token, 'method' => $method));
$client = \Drupal::httpClient();
// Do not wait for a response.
$client->addSubscriber(new AsyncPlugin());
$url = $this->url('feeds.execute', array('feeds_feed' => $feed->id()), array('absolute' => TRUE));
$request = $client->post($url)->addPostFields(array('token' => $token));
$request->send();
}
示例8: setUp
protected function setUp()
{
parent::setUp();
// Create Basic page node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
}
$this->privilegedUser = $this->drupalCreateUser(array('administer statistics', 'view post access counter', 'create page content'));
$this->drupalLogin($this->privilegedUser);
$this->testNode = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->privilegedUser->id()));
$this->client = \Drupal::httpClient();
$this->client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10));
}
示例9: content
/**
* Generates an example page.
*/
public function content()
{
// Get module configuration.
$module_config = \Drupal::config('weather.settings');
$this->key = $module_config->get('key');
// Create a HTTP client.
$client = \Drupal::httpClient();
// Set default options.
$client->setDefaultOption('timeout', self::WEATHER_TIMEOUT);
// Create a request GET object.
$request = $client->createRequest('GET', self::WEATHER_API_URL);
// Filter on Key.
if ($this->key != '') {
$filter = "SecureGuid eq '" . $this->key . "'";
} else {
drupal_set_message('Set up you IBP Catalog key', 'status', TRUE);
return FALSE;
}
// Add a few query strings.
$query = $request->getQuery();
$query->set('$filter', $filter);
try {
$response = $client->send($request);
} catch (RequestException $e) {
drupal_set_message('Bad request', 'error', TRUE);
return FALSE;
} catch (\Exception $e) {
drupal_set_message('Bad request', 'error', TRUE);
return FALSE;
}
// If success.
if ($response->getStatusCode() == 200) {
// We are expecting XML content.
$xml = $response->xml();
$compt = 0;
foreach ($xml->xpath('//m:properties') as $properties) {
$d = $properties->children('http://schemas.microsoft.com/ado/2007/08/dataservices');
$rows[$compt]['url'] = String::checkPlain($d->CalculatedUrl);
$rows[$compt]['language'] = String::checkPlain($d->Language);
$rows[$compt]['subcategoryfr'] = String::checkPlain($d->SubCategoryFR);
$rows[$compt]['friendlysizekey'] = String::checkPlain($d->FriendlySizeKey);
$rows[$compt]['productdomaincodedescriptionfr'] = String::checkPlain($d->ProductDomainCodeDescriptionFR);
$rows[$compt++]['companyname'] = String::checkPlain($d->CompanyName);
}
}
$header = array('URL', 'Language', 'Category Description', 'FriendlySizeKey', 'Product', 'Company');
$table = array('#type' => 'table', '#header' => $header, '#rows' => $rows, '#attributes' => array('id' => 'book-outline'), '#empty' => t('No item available.'));
return drupal_render($table);
}
示例10: response
/**
* Generates an example page.
*/
public function response($date, $location, $hourly_interval)
{
/**
* Weather API URL.
*/
$WEATHER_API_URL = 'http://api.worldweatheronline.com/free/v2/weather.ashx?q=' . $location . '&date=' . $date . '&tp=' . $hourly_interval . '&key=ade5f8b9d77a3eb016b7515df6464&format=json';
// Create a HTTP client.
$client = \Drupal::httpClient();
// Create a request GET object.
$response = $client->get($WEATHER_API_URL);
#$request = $client->createRequest('GET', self::WEATHER_API_URL, []);
if ($response->getStatusCode() == 200) {
return json_decode($response->getBody(), TRUE);
}
}
示例11: decode
public function decode($url)
{
// Clients will only throw exceptions that are a subclass of GuzzleHttp\Exception\RequestException.
try {
// Create a HTTP client.
$response = \Drupal::httpClient()->get($url)->getBody(TRUE);
} catch (RequestException $e) {
// Do some stuff in case of the error.
}
// If successful HTTP query.
if ($response) {
$data = $response->getContents();
return Json::decode($data);
} else {
return NULL;
}
}
示例12: setUp
protected function setUp()
{
parent::setUp();
// Create Basic page node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
}
$this->authUser = $this->drupalCreateUser(array('access content', 'create page content', 'edit own page content'));
// Ensure we have a node page to access.
$this->node = $this->drupalCreateNode(array('title' => $this->randomMachineName(255), 'uid' => $this->authUser->id()));
// Enable access logging.
$this->config('statistics.settings')->set('count_content_views', 1)->save();
// Clear the logs.
db_truncate('node_counter');
$this->client = \Drupal::httpClient();
$this->client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10));
}
示例13: zoho_generate_authtoken
/**
* Generates a new ZOHO Auth Token and stores in db.
*
* @param string $username
* User name of the Zoho crm account
* @param string $pass
* Password for Zoho crm account
*
* @returns array
* Returns an array with authtoken if success and error otherwise.
*/
function zoho_generate_authtoken($username, $pass)
{
$url = ZOHO_TICKET_URL . "apiauthtoken/nb/create?SCOPE=ZohoCRM/crmapi&EMAIL_ID=" . $username . "&PASSWORD=" . $pass;
try {
$response = \Drupal::httpClient()->get($url, array('headers' => array('Accept' => 'text/plain')));
$result = (string) $response->getBody();
$anarray = explode("\n", $result);
$authtoken = explode("=", $anarray['2']);
$cmp = strcmp($authtoken['0'], "AUTHTOKEN");
if ($cmp == 0) {
return array('authtoken' => $authtoken['1']);
} else {
return array('error' => $authtoken['1']);
}
} catch (RequestException $ex) {
watchdog_exception('zoho', $ex);
return array('error' => $ex);
}
}
示例14: build
/**
* {@inheritdoc}
*/
public function build()
{
$config = $this->getConfiguration();
if (!empty($config['unibuc_weather_api_key'])) {
$url = 'http://api.openweathermap.org/data/2.5/forecast/city?id=683506&APPID=' . $config['unibuc_weather_api_key'];
$data = (string) \Drupal::httpClient()->get($url)->getBody();
$data = json_decode($data);
$temp = $data->list[0]->main->temp;
$degree = $config['unibuc_weather_api_display'];
if ($config['unibuc_weather_api_display'] == 'c') {
$temp = $temp - 273;
} else {
$temp = $temp * 9 / 5 - 460;
}
return array('#markup' => $this->t('The temperature in @city is @temp @degree', array('@city' => 'Bucharest', '@temp' => $temp, '@degree' => strtoupper($degree))));
} else {
return array('#markup' => $this->t("Please set your API Key from <a target='_blank' href='http://openweathermap.org/'>openweathermap.org</a>"));
}
}
示例15: testNodeCounterIntegration
/**
* Tests the integration of the {node_counter} table in views.
*/
public function testNodeCounterIntegration()
{
$this->drupalGet('node/' . $this->node->id());
// Manually calling statistics.php, simulating ajax behavior.
// @see \Drupal\statistics\Tests\StatisticsLoggingTest::testLogging().
global $base_url;
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$client = \Drupal::httpClient();
$client->setDefaultOption('config/curl', array(CURLOPT_TIMEOUT => 10));
$client->post($stats_path, array('body' => array('nid' => $this->node->id())));
$this->drupalGet('test_statistics_integration');
$expected = statistics_get($this->node->id());
// Convert the timestamp to year, to match the expected output of the date
// handler.
$expected['timestamp'] = date('Y', $expected['timestamp']);
foreach ($expected as $field => $value) {
$xpath = "//div[contains(@class, views-field-{$field})]/span[@class = 'field-content']";
$this->assertFieldByXpath($xpath, $value, "The {$field} output matches the expected.");
}
}