示例#1
0
 /**
  * Make the call to the endpoint and get the result
  *
  * @param string $url The URL to call
  * @param string $method The verb to use
  * @param array $params An array of parameters
  *
  * @return array The result in php array
  */
 private function call($url, $method, $params = null)
 {
     $request = $this->client->createRequest($method, $this->getEndpoint() . $url);
     $request->setHeader('Content-Type', 'application/' . $this->format);
     $request->setHeader('Accept', 'application/' . $this->format);
     $request->setHeader('Authorization', 'Basic ' . base64_encode($this->username . "/token:" . $this->api_key));
     if ($params) {
         $request->setBody(Stream::factory(json_encode($params)));
     }
     $response = $this->client->send($request);
     return json_decode($response->getBody());
 }
示例#2
0
 public function getRecipientViewUrl($returnUrl)
 {
     $data = array("email" => $this->studentEmail, "returnUrl" => $returnUrl, "authenticationMethod" => "None", "userName" => $this->studentName, "clientUserId" => $this->clientUserId);
     //var_dump($data);
     //exit;
     $http = new \Guzzle\Http\Client();
     try {
         //$request = $http->createRequest('POST', $this->client->getBaseUrl() . $this->envelope->getUri() . '/views/recipient', ['body' => json_encode($data)]);
         $request = $http->createRequest('POST', $this->client->getBaseUrl() . $this->envelope->getUri() . '/views/recipient');
         $request->setBody(json_encode($data), 'application/json');
         $request->setHeader('Content-Type', 'application/json');
         $request->setHeader('Accept', 'application/json');
         $request->setHeader('X-DocuSign-Authentication', $this->client->getAuthHeader());
         $response = $http->send($request);
     } catch (\Guzzle\Http\Exception\RequestException $e) {
         //var_dump($e->getResponse()->json());
         //var_dump($e);
         //var_dump($e->getRequest());
         //exit;
         throw $e;
     }
     $result = $response->json();
     //var_dump($result);exit;
     return $result['url'];
 }
 /**
  * @inheritDoc ITask::runStep()
  *
  * @param int $step
  *
  * @return bool
  */
 public function runStep($step)
 {
     // NOTE: Perhaps much of this should be moved into a service
     $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build();
     // Make the client
     $client = new \Guzzle\Http\Client();
     // Set the Accept header
     $client->setDefaultOption('headers/Accept', '*/*');
     // Loop the paths in this step
     foreach ($this->_paths[$step] as $path) {
         // Make the url, stripping 'site:' from the path if it exists
         $newPath = preg_replace('/site:/', '', $path, 1);
         $url = UrlHelper::getSiteUrl($newPath);
         // Create the PURGE request
         $request = $client->createRequest('PURGE', $url);
         // Add it to the batch
         $batch->add($request);
     }
     // Flush the queue and retrieve the flushed items
     $requests = $batch->flush();
     // Log any exceptions
     foreach ($batch->getExceptions() as $e) {
         Craft::log('CacheMonster: an exception occurred: ' . $e->getMessage(), LogLevel::Error);
     }
     // Clear any exceptions
     $batch->clearExceptions();
     return true;
 }
 public function runStep($step)
 {
     VarnishpurgePlugin::log('Varnish purge task run step: ' . $step, LogLevel::Info, craft()->varnishpurge->getSetting('varnishLogAll'));
     $servers = craft()->varnishpurge->getSetting('varnishUrl');
     if (!is_array($servers)) {
         $servers = array($servers);
     }
     foreach ($servers as $server) {
         $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build();
         $client = new \Guzzle\Http\Client();
         $client->setDefaultOption('headers/Accept', '*/*');
         foreach ($this->_urls[$step] as $url) {
             $urlComponents = parse_url($url);
             $targetUrl = preg_replace('{/$}', '', $server) . $urlComponents['path'];
             VarnishpurgePlugin::log('Adding url to purge: ' . $targetUrl . ' with Host: ' . $urlComponents['host'], LogLevel::Info, craft()->varnishpurge->getSetting('varnishLogAll'));
             $request = $client->createRequest('PURGE', $targetUrl);
             $request->addHeader('Host', $urlComponents['host']);
             $batch->add($request);
         }
         $requests = $batch->flush();
         foreach ($batch->getExceptions() as $e) {
             VarnishpurgePlugin::log('An exception occurred: ' . $e->getMessage(), LogLevel::Error);
         }
         $batch->clearExceptions();
     }
     return true;
 }
 /**
  * Sends a request and returns a response
  *
  * @param CartRecover_Request $request
  * @return Cart_Recover_Response
  */
 public function sendRequest(CartRecover_Request $request)
 {
     $url = Guzzle\Http\Url::factory($request->getUri());
     $url->setQuery($request->getParams());
     $this->client->setBaseUrl($url);
     $grequest = $this->client->createRequest($request->getMethod(), $url);
     $grequest->addHeader('Accept', 'application/json');
     $this->response = $this->client->send($grequest);
     if (!$this->response->isContentType('application/json')) {
         throw new CartRecover_Exception_UnexpectedValueException("Unknown response format.");
     }
     $response = new CartRecover_Response();
     $response->setRawResponse($this->response->__toString());
     $response->setBody($this->response->json());
     $response->setHeaders($this->response->getHeaders()->toArray());
     $response->setStatus($this->response->getReasonPhrase(), $this->response->getStatusCode());
     return $response;
 }
示例#6
0
 public static function getEnvelopeById(Client $client, $envelopeId)
 {
     $http = new \Guzzle\Http\Client();
     try {
         $request = $http->createRequest('GET', $client->getBaseUrl() . '/envelopes/' . $envelopeId);
         $request->setHeader('Content-Type', 'application/json');
         $request->setHeader('Accept', 'application/json');
         $request->setHeader('X-DocuSign-Authentication', $client->getAuthHeader());
         $response = $http->send($request);
     } catch (\GuzzleHttp\Exception\RequestException $e) {
         throw new \Exception(print_r($e->getResponse()->json(), true));
     }
     $result = $response->json();
     $envelope = new Envelope($result['envelopeId'], '/envelopes/' . $envelopeId, $result['statusChangedDateTime'], $result['status']);
     return $envelope;
 }
 public function runStep($step)
 {
     VarnishpurgePlugin::log('Varnish purge task run step: ' . $step, LogLevel::Info, craft()->varnishpurge->getSetting('varnishLogAll'));
     $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build();
     $client = new \Guzzle\Http\Client();
     $client->setDefaultOption('headers/Accept', '*/*');
     foreach ($this->_urls[$step] as $url) {
         VarnishpurgePlugin::log('Adding url to purge: ' . $url, LogLevel::Info, craft()->varnishpurge->getSetting('varnishLogAll'));
         $request = $client->createRequest('PURGE', $url);
         $batch->add($request);
     }
     $requests = $batch->flush();
     foreach ($batch->getExceptions() as $e) {
         VarnishpurgePlugin::log('An exception occurred: ' . $e->getMessage(), LogLevel::Error);
     }
     $batch->clearExceptions();
     return true;
 }
示例#8
0
 public function authenticate()
 {
     $url = $this->getAPIUrl() . '/login_information';
     $http = new \Guzzle\Http\Client();
     try {
         $request = $http->createRequest('GET', $url);
         $request->setHeader('Content-Type', 'application/json');
         $request->setHeader('Accept', 'application/json');
         $request->setHeader('X-DocuSign-Authentication', $this->getAuthHeader());
         $response = $http->send($request);
     } catch (\GuzzleHttp\Exception\RequestException $e) {
         //var_dump($e);
         //var_dump($e->getRequest());
         //exit;
         throw $e;
     }
     $json = $response->json();
     //var_dump($json);exit;
     //var_dump($json['loginAccounts'][0]['baseUrl']);
     $this->baseURL = $json['loginAccounts'][0]['baseUrl'];
     $this->accountID = $json['loginAccounts'][0]['accountId'];
     /*
     if( count($response->loginAccounts) > 1 ) $this->hasMultipleAccounts = true;
     $defaultBaseURL = '';
     $defaultAccountID = '';
     foreach($response->loginAccounts as $account) {
         if( !empty($this->accountID) ) {
             if( $this->accountID == $account->accountId ) {
                 $this->baseURL = $account->baseUrl;
                 break;
             }
         }
         if( $account->isDefault == 'true' ) {
             $defaultBaseURL = $account->baseUrl;
             $defaultAccountID = $account->accountId;
         }
     }
     if(empty($this->baseURL)) {
         $this->baseURL = $defaultBaseURL;
         $this->accountID = $defaultAccountID;
     }
     */
 }
/**
 * Overrides Drupal core HTTP request function with Guzzle.
 *
 * @see drupal_http_request()
 */
function bangpound_drupal_http_request($url, array $options = array())
{
    $result = new stdClass();
    // Parse the URL and make sure we can handle the schema.
    $uri = @parse_url($url);
    if ($uri == FALSE) {
        $result->error = 'unable to parse URL';
        $result->code = -1001;
        return $result;
    }
    if (!isset($uri['scheme'])) {
        $result->error = 'missing schema';
        $result->code = -1002;
        return $result;
    }
    timer_start(__FUNCTION__);
    // Merge the default options.
    $options += array('headers' => array(), 'method' => 'GET', 'data' => NULL, 'max_redirects' => 3, 'timeout' => 30.0, 'context' => NULL);
    // Merge the default headers.
    $options['headers'] += array('User-Agent' => 'Drupal (+http://drupal.org/)');
    // Concessions to Guzzle.
    if (isset($options['data'])) {
        $options['body'] = $options['data'];
    }
    if (!$options['max_redirects']) {
        $options['allow_redirects'] = FALSE;
    }
    // Use a proxy if one is defined and the host is not on the excluded list.
    $proxy_server = variable_get('proxy_server', '');
    if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
        // Set the scheme so we open a socket to the proxy server.
        $uri['scheme'] = 'proxy';
        // Set the path to be the full URL.
        $uri['path'] = $url;
        // Since the URL is passed as the path, we won't use the parsed query.
        unset($uri['query']);
        // Add in username and password to Proxy-Authorization header if needed.
        if ($proxy_username = variable_get('proxy_username', '')) {
            $proxy_password = variable_get('proxy_password', '');
            $options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
        }
        // Some proxies reject requests with any User-Agent headers, while others
        // require a specific one.
        $proxy_user_agent = variable_get('proxy_user_agent', '');
        // The default value matches neither condition.
        if ($proxy_user_agent === NULL) {
            unset($options['headers']['User-Agent']);
        } elseif ($proxy_user_agent) {
            $options['headers']['User-Agent'] = $proxy_user_agent;
        }
    }
    // Make sure the socket opened properly.
    // @todo Migrate error checking.
    // If the server URL has a user then attempt to use basic authentication.
    // @todo Migrate authentication.
    // If the database prefix is being used by SimpleTest to run the tests in a copied
    // database then set the user-agent header to the database prefix so that any
    // calls to other Drupal pages will run the SimpleTest prefixed database. The
    // user-agent is used to ensure that multiple testing sessions running at the
    // same time won't interfere with each other as they would if the database
    // prefix were stored statically in a file or database variable.
    $test_info =& $GLOBALS['drupal_test_info'];
    if (!empty($test_info['test_run_id'])) {
        $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
    }
    // Calculate how much time is left of the original timeout value.
    $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
    if ($timeout > 0) {
        /** @see \Guzzle\Http\StaticClient::request() */
        static $client;
        if (!$client) {
            $client = new \Guzzle\Http\Client();
        }
        $request = $client->createRequest($options['method'], $url, null, null, $options);
        if ($options['max_redirects']) {
            $client->getConfig()->set('redirect.max', $options['max_redirects']);
        }
        if (isset($options['stream'])) {
            if ($options['stream'] instanceof \Guzzle\Stream\StreamRequestFactoryInterface) {
                $response = $options['stream']->fromRequest($request);
            } elseif ($options['stream'] == true) {
                $streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
                $response = $streamFactory->fromRequest($request);
            }
        } else {
            $response = $request->send();
        }
        $result->request = $request->__toString();
    } else {
        $result->code = HTTP_REQUEST_TIMEOUT;
        $result->error = 'request timed out';
        return $result;
    }
    if (isset($response)) {
        // Parse response headers from the response body.
        // Be tolerant of malformed HTTP responses that separate header and body with
        // \n\n or \r\r instead of \r\n\r\n.
        $result->data = $response->getBody(true);
        // Parse the response status line.
        $result->protocol = $response->getProtocol() . '/' . $response->getProtocolVersion();
        $result->status_message = $response->getReasonPhrase();
        $result->headers = array_map(function ($input) {
            return (string) $input;
        }, $response->getHeaders()->getAll());
        $result->code = $response->getStatusCode();
        switch ($result->code) {
            case 200:
                // OK
            // OK
            case 304:
                // Not modified
                break;
            case 301:
                // Moved permanently
            // Moved permanently
            case 302:
                // Moved temporarily
            // Moved temporarily
            case 307:
                // Moved temporarily
                // $result->redirect_code = $code;
                // $result->redirect_url = $location;
                break;
            default:
                $result->error = $response->getReasonPhrase();
        }
    }
    return $result;
}
示例#10
0
<?php

require '../vendor/autoload.php';
$amount = 1000;
$json = '{
  "name": "order.creation.fr",
  "identifier": 1484393,
  "data": "{\\"id\\":1029102,\\"title\\":\\"hello\\"}",
  "contentType": "application/json"
}';
$client = new \Guzzle\Http\Client();
$times = [];
for ($i = 0; $i < $amount; $i++) {
    $t = microtime(true);
    try {
        $request = $client->createRequest('POST', 'http://eventbus.exaprint.localhost/events', ['Content-Type' => 'application/json', 'Accept' => 'application/json'], $json, ["future" => true]);
        $request->send();
    } catch (\Guzzle\Http\Exception\ServerErrorResponseException $serverError) {
        echo $serverError->getResponse()->getBody();
        die;
    } catch (HttpResponseException $httpError) {
    }
    $times[] = microtime(true) - $t;
}
echo array_sum($times) / count($times);