resetParameters() public method

Should be used to reset the request parameters if the client is used for several concurrent requests. clearAll parameter controls if we clean just parameters or also headers and last_*
public resetParameters ( boolean $clearAll = false ) : Zend_Http_Client
$clearAll boolean Should all data be cleared?
return Zend_Http_Client
コード例 #1
0
ファイル: PayPal.php プロジェクト: jorgenils/zend-framework
 /**
  * HTTP client preparation procedures - should be called before every API 
  * call. 
  * 
  * Will clean up the HTTP client parameters, set the request method to POST
  * and add the always-required authentication information
  * 
  * @param  string $method The API method we are about to use
  * @return void
  */
 protected function prepare($method)
 {
     // Reset parameters
     $this->httpClient->resetParameters();
     // Add authentication data
     $this->httpClient->setMethod('POST');
     $this->httpClient->setParameterPost(array('USER' => $this->authInfo->getUser(), 'PWD' => $this->authInfo->getPassword(), 'SIGNATURE' => $this->authInfo->getSignature(), 'VERSION' => '2.3', 'METHOD' => $method));
 }
コード例 #2
0
ファイル: Ru.php プロジェクト: xiaoguizhidao/ortodon
 /**
  * @return Zend_Http_Client
  */
 protected function _getClient()
 {
     if (is_null($this->_httpClient)) {
         if (!$this->_apiUri) {
             Mage::throwException('Please specify API uri.');
         }
         $this->_httpClient = new Zend_Http_Client($this->_apiUri);
     }
     return $this->_httpClient->resetParameters(true);
 }
コード例 #3
0
 /**
  * Return the singleton instance of the HTTP Client. Note that
  * the instance is reset and cleared of previous parameters and
  * Authorization header values.
  *
  * @return Zend_Http_Client
  */
 public static function getHttpClient()
 {
     if (!isset(self::$httpClient)) {
         self::$httpClient = new Zend_Http_Client();
     } else {
         self::$httpClient->setHeaders('Authorization', null);
         self::$httpClient->resetParameters();
     }
     return self::$httpClient;
 }
コード例 #4
0
ファイル: Zend1HttpAdapter.php プロジェクト: lamenath/fbp
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $this->client->resetParameters(true)->setConfig(array('httpversion' => $internalRequest->getProtocolVersion(), 'timeout' => $this->getConfiguration()->getTimeout(), 'maxredirects' => 0))->setUri($url = (string) $internalRequest->getUrl())->setMethod($internalRequest->getMethod())->setHeaders($this->prepareHeaders($internalRequest))->setRawData($this->prepareBody($internalRequest));
     try {
         $response = $this->client->request();
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse($response->getStatus(), $response->getMessage(), $response->getVersion(), $response->getHeaders(), BodyNormalizer::normalize(function () use($response) {
         return $response instanceof \Zend_Http_Response_Stream ? $response->getStream() : $response->getBody();
     }, $internalRequest->getMethod()));
 }
コード例 #5
0
 /**
  * Execute CheddarGetter API request
  *
  * @param string $url Url to the API action
  * @param string $username Username
  * @param string $password Password
  * @param array|null $args HTTP post key value pairs
  * @return string Body of the response from the CheddarGetter API
  * @throws Zend_Http_Client_Exception A Zend_Http_Client_Exception may
  * be thrown under a number of conditions but most likely if the tcp socket
  * fails to connect.
  */
 public function request($url, $username, $password, array $args = null)
 {
     // reset
     $this->_client->setUri($url);
     $this->_client->resetParameters();
     $this->_client->setMethod(Zend_Http_Client::GET);
     $this->_client->setAuth($username, $password);
     if ($args) {
         $this->_client->setMethod(Zend_Http_Client::POST);
         $this->_client->setParameterPost($args);
     }
     $response = $this->_client->request();
     return $response->getBody();
 }
コード例 #6
0
ファイル: Mobypicture.php プロジェクト: hausdesign/zf-library
 /**
  * Post a comment.
  *
  * @param string $code
  * @param string $message
  * @param array $options
  * @param string $format
  */
 public function postComment($code, $message, $options = array(), $format = self::FORMAT_XML)
 {
     $defaults = array('name' => '', 'email' => '', 'tweet' => 0);
     $options = array_merge($defaults, $options);
     if (!strlen($options['name']) && !strlen($options['email'])) {
         if (null == $this->_username && null == $this->_password) {
             throw new HausDesign_Service_Mobypicture_Exception('name and email or username and password should by defined');
         }
     }
     $this->_localHttpClient->resetParameters();
     $this->_localHttpClient->setUri(self::MOBYPICTURE_API);
     $this->_localHttpClient->setParameterGet('action', 'postComment');
     if (!strlen($options['name']) && !strlen($options['email'])) {
         $this->_localHttpClient->setParameterGet('u', $this->_username);
         $this->_localHttpClient->setParameterGet('p', $this->_password);
     }
     $this->_localHttpClient->setParameterGet('k', $this->_apiKey);
     $this->_localHttpClient->setParameterGet('tinyurl_code ', $code);
     $this->_localHttpClient->setParameterGet('message', $code);
     $this->_localHttpClient->setParameterGet('format', $format);
     foreach ($options as $option => $value) {
         $this->_localHttpClient->setParameterGet($option, $value);
     }
     return $this->_parseContent($this->_localHttpClient->request('GET')->getBody(), $format);
 }
コード例 #7
0
ファイル: Gdata.php プロジェクト: josephholsten/swaplady
 /**
  * Retreive feed object
  *
  * @param string $uri
  * @return Zend_Feed
  */
 public function getFeed($uri)
 {
     $feed = new Zend_Feed();
     $this->_httpClient->resetParameters();
     $feed->setHttpClient($this->_httpClient);
     return $feed->import($uri);
 }
コード例 #8
0
ファイル: CommonHttpTests.php プロジェクト: nbcutech/o3drupal
    /**
     * Make sure we can reset the parameters between consecutive requests
     *
     */
    public function testResetParameters()
    {
        $params = array(
            'quest' => 'To seek the holy grail',
            'YourMother' => 'Was a hamster',
            'specialChars' => '<>$+ &?=[]^%',
            'array' => array('firstItem', 'secondItem', '3rdItem')
        );

        $headers = array("X-Foo" => "bar");

        $this->client->setParameterPost($params);
        $this->client->setParameterGet($params);
        $this->client->setHeaders($headers);

        $res = $this->client->request('POST');

        $this->assertContains(serialize($params) . "\n" . serialize($params),
            $res->getBody(), "returned body does not contain all GET and POST parameters (it should!)");

        $this->client->resetParameters();
        $res = $this->client->request('POST');

        $this->assertNotContains(serialize($params), $res->getBody(),
            "returned body contains GET or POST parameters (it shouldn't!)");
        $this->assertContains($headers["X-Foo"], $this->client->getHeader("X-Foo"), "Header not preserved by reset");

        $this->client->resetParameters(true);
        $this->assertNull($this->client->getHeader("X-Foo"), "Header preserved by reset(true)");
    }
コード例 #9
0
ファイル: Api.php プロジェクト: noglance/ZF-Vkontakte-SDK
 /**
  * Makes request and checks the result according uri
  *
  * @param  string $uri
  * @return stdClass
  * @throws \Exception when the result was unsuccessful
  * @throws \UnexpectedValueException JSON parsing error
  */
 protected function _request($uri)
 {
     // request object
     $request = $this->_httpClient->resetParameters(true)->setUri($uri);
     // let's send request and check what we have
     try {
         $response = $request->request();
     } catch (\Zend_Http_Client_Exception $e) {
         throw new \Exception('Client request was unsuccessful', $e->getCode(), $e);
     }
     if (!$response->isSuccessful()) {
         throw new \Exception("Request failed({$response->getStatus()}): {$response->getMessage()} at " . $request->getLastRequest());
     }
     // the response has JSON format, we should decode it
     try {
         $decoded = \Zend_Json::decode($response->getBody(), \Zend_Json::TYPE_OBJECT);
     } catch (\Zend_Json_Exception $e) {
         throw new \UnexpectedValueException('Response is not JSON: ' . $response->getBody());
     }
     // do we have something interesting?
     if (isset($decoded->error)) {
         if (!isset($decoded->error->error_code)) {
             $this->_errorMessage = $decoded->error;
         } else {
             throw new \Exception("Response contains error({$decoded->error->error_code}): " . $decoded->error->error_msg);
         }
     }
     return $decoded;
 }
コード例 #10
0
ファイル: Consumer.php プロジェクト: highfidelity/love
 /**
  * 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;
     }
 }
コード例 #11
0
ファイル: Pubsubhubbub.php プロジェクト: nhp/shopware-4
 /**
  * Return the singleton instance of the HTTP Client. Note that
  * the instance is reset and cleared of previous parameters GET/POST.
  * Headers are NOT reset but handled by this component if applicable.
  *
  * @return Zend_Http_Client
  */
 public static function getHttpClient()
 {
     if (!isset(self::$httpClient)):
         self::$httpClient = new Zend_Http_Client;
     else:
         self::$httpClient->resetParameters();
     endif;
     return self::$httpClient;
 }
コード例 #12
0
ファイル: HttpBox.php プロジェクト: bsa-git/zf-myblog
 /**
  * Clear all GET and POST parameters
  *
  * Should be used to reset the request parameters if the client is
  * used for several concurrent requests.
  *
  * clearAll parameter controls if we clean just parameters or also
  * headers and last_*
  *
  * @param bool $clearAll Should all data be cleared?
  * @return Default_Plugin_HttpBox
  */
 function resetParameters($clearAll = false)
 {
     $this->last_url = null;
     $this->last_request = null;
     $this->last_response = null;
     $this->last_cookies = null;
     $this->last_config = null;
     $this->client->resetParameters($clearAll);
     return $this;
 }
コード例 #13
0
ファイル: App.php プロジェクト: dalinhuang/popo
 /**
  * DELETE entry with client object
  *
  * @param mixed $data The Zend_Gdata_App_Entry or URL to delete
  * @return void
  * @throws Zend_Gdata_App_Exception
  * @throws Zend_Gdata_App_HttpException
  * @throws Zend_Gdata_App_InvalidArgumentException
  */
 public function delete($data, $remainingRedirects = null)
 {
     require_once 'Zend/Http/Client/Exception.php';
     if ($remainingRedirects === null) {
         $remainingRedirects = self::getMaxRedirects();
     }
     if (is_string($data)) {
         $uri = $data;
     } elseif ($data instanceof Zend_Gdata_App_Entry) {
         $editLink = $data->getEditLink();
         if ($editLink != null) {
             $uri = $editLink->getHref();
         }
     } else {
         require_once 'Zend/Gdata/App/InvalidArgumentException.php';
         throw new Zend_Gdata_App_InvalidArgumentException('You must specify the data to post as either a string or a child of Zend_Gdata_App_Entry');
     }
     if ($uri === null) {
         require_once 'Zend/Gdata/App/InvalidArgumentException.php';
         throw new Zend_Gdata_App_InvalidArgumentException('You must specify an URI which needs deleted.');
     }
     $this->_httpClient->resetParameters();
     $this->_httpClient->setHeaders('x-http-method-override', null);
     $this->_httpClient->setUri($uri);
     $this->_httpClient->setConfig(array('maxredirects' => 0));
     try {
         if (Zend_Gdata_App::getHttpMethodOverride()) {
             $this->_httpClient->setHeaders(array('X-HTTP-Method-Override: DELETE'));
             $this->_httpClient->setRawData('');
             $response = $this->_httpClient->request('POST');
         } else {
             $response = $this->_httpClient->request('DELETE');
         }
     } catch (Zend_Http_Client_Exception $e) {
         require_once 'Zend/Gdata/App/HttpException.php';
         throw new Zend_Gdata_App_HttpException($e->getMessage(), $e);
     }
     if ($response->isRedirect()) {
         if ($remainingRedirects > 0) {
             $newUri = $response->getHeader('Location');
             $response = $this->delete($newUri, $remainingRedirects - 1);
         } else {
             require_once 'Zend/Gdata/App/HttpException.php';
             throw new Zend_Gdata_App_HttpException('No more redirects allowed', null, $response);
         }
     }
     if (!$response->isSuccessful()) {
         require_once 'Zend/Gdata/App/HttpException.php';
         $exception = new Zend_Gdata_App_HttpException('Expected response code 200, got ' . $response->getStatus());
         $exception->setResponse($response);
         throw $exception;
     }
     return $response;
 }
コード例 #14
0
 /**
  * private getter for the Zend_Http_Client
  * if not set yet it will be instantiated
  *
  * @return Zend_Http_Client
  */
 protected function _getZendHttpClient()
 {
     if (is_null($this->_httpClient)) {
         // @todo implement SSL check here
         $this->_httpClient = new Zend_Http_Client($this->_getRequestUrl());
     } else {
         $this->_httpClient->resetParameters(true);
         $this->_httpClient->setUri($this->_getRequestUrl());
     }
     return $this->_httpClient;
 }
コード例 #15
0
 /**
  * Login to the API, set the auth header.
  * @throws Zend_Http_Client_Exception
  * @throws Exception
  */
 protected function login()
 {
     $this->client->setUri($this->config['uri'] . $this->config['endpoints']['auth']);
     $this->client->setParameterPost($this->config['credentials']);
     $response = $this->client->request('POST');
     if ($response->getStatus() > 299) {
         throw new Exception('Unable to login, user credentials in config incorrect');
     }
     $jsonResponse = json_decode($response->getBody(), true);
     $this->client->resetParameters();
     $this->client->setHeaders('Authorization', 'Bearer ' . $jsonResponse['access_token']);
 }
コード例 #16
0
ファイル: Base.php プロジェクト: netconstructor/Centurion
 /**
  * When a method call is made against this proxy, convert it to
  * an HTTP request to make against the Nirvanix REST service.
  *
  * $imfs->DeleteFiles(array('filePath' => 'foo'));
  *
  * Assuming this object was proxying the IMFS namespace, the
  * method call above would call the DeleteFiles command.  The
  * POST parameters would be filePath, merged with the
  * $this->_defaults (containing the sessionToken).
  *
  * @param  string  $methodName  Name of the command to call
  *                              on this namespace.
  * @param  array   $args        Only the first is used and it must be
  *                              an array.  It contains the POST params.
  *
  * @return Zend_Service_Nirvanix_Response
  */
 public function __call($methodName, $args)
 {
     $uri = $this->_makeUri($methodName);
     $this->_httpClient->setUri($uri);
     if (!isset($args[0]) || !is_array($args[0])) {
         $args[0] = array();
     }
     $params = array_merge($this->_defaults, $args[0]);
     $this->_httpClient->resetParameters();
     $this->_httpClient->setParameterPost($params);
     $httpResponse = $this->_httpClient->request(Zend_Http_Client::POST);
     return $this->_wrapResponse($httpResponse);
 }
コード例 #17
0
ファイル: Bot.php プロジェクト: hhatfield/hermes
 public function listenRoom($room)
 {
     $this->joinRoom($room);
     $uri = 'https://' . $this->subdomain . '.campfirenow.com/room/' . $room . '/recent.json';
     $lastMessageId = null;
     while (true) {
         $this->client->resetParameters();
         if (!is_null($lastMessageId)) {
             $this->client->setParameterGet('since_message_id', $lastMessageId);
         } else {
             $this->client->setParameterGet('limit', 1);
         }
         $this->client->setUri($uri);
         $this->client->setMethod(Zend_Http_Client::GET);
         $response = $this->client->request();
         $newMessageId = $this->processMessages($response);
         if ($newMessageId > $lastMessageId) {
             $lastMessageId = $newMessageId;
         }
         sleep(1);
     }
     return (bool) ($response->getStatus() == 200);
 }
コード例 #18
0
ファイル: Tokio.php プロジェクト: rtsantos/mais
 /**
  * 
  * @param string $url
  * @param array $param
  * @param string $method
  * @return string
  */
 protected function _request($url, $param = array(), $method = Zend_Http_Client::POST)
 {
     if ($this->_client === null) {
         $config = array('useragent' => 'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/44.0', 'encodecookies' => false, 'timeout' => 180);
         $this->_client = new Zend_Http_Client($url, $config);
         $this->_client->setCookieJar();
     }
     $this->_client->resetParameters()->setUri($url);
     if (count($param['post']) > 0) {
         foreach ($param['post'] as $name => $value) {
             $this->_client->setParameterPost($name, $value);
         }
     }
     if (count($param['get']) > 0) {
         foreach ($param['get'] as $name => $value) {
             $this->_client->setParameterPost($name, $value);
         }
     }
     if (count($param['file']) > 0) {
         foreach ($param['file'] as $name => $value) {
             $this->_client->setFileUpload($value, $name);
         }
     }
     if (count($param['cookie']) > 0) {
         foreach ($param['cookie'] as $name => $value) {
             $this->_client->setCookie($name, $value);
         }
     }
     if (count($this->_cookies) > 0) {
         foreach ($this->_cookies as $cookie) {
             $this->_client->setCookie($cookie);
         }
     }
     $response = $this->_client->request($method);
     $this->_cookies = $this->_client->getCookieJar()->getAllCookies();
     return $response->getBody();
 }
コード例 #19
0
 /**
  * @group ZF-11418
  */
 public function testMultiplePuts()
 {
     $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
     $data = 'test';
     $this->client->setRawData($data, 'text/plain');
     $this->client->setMethod(Zend_Http_Client::PUT);
     $response = $this->client->request();
     $this->assertContains('REQUEST_METHOD: PUT', $response->getBody(), $response->getBody());
     $this->client->resetParameters(true);
     $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
     $this->client->setMethod(Zend_Http_Client::PUT);
     $response = $this->client->request();
     $request = $this->client->getLastRequest();
     $this->assertNotContains('Content-Type: text/plain', $request);
 }
コード例 #20
0
ファイル: Twitter.php プロジェクト: hjr3/zf2
 /**
  * Call a remote REST web service URI and return the Zend_Http_Response object
  *
  * @param  string $path            The path to append to the URI
  * @throws Zend_Rest_Client_Exception
  * @return void
  */
 protected function _prepare($path)
 {
     // Get the URI object and configure it
     if (!$this->_uri instanceof Zend_Uri_Http) {
         throw new Zend_Rest_Client_Exception('URI object must be set before performing call');
     }
     $uri = $this->_uri->getUri();
     if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') {
         $path = '/' . $path;
     }
     $this->_uri->setPath($path);
     /**
      * Get the HTTP client and configure it for the endpoint URI.  Do this each time
      * because the Zend_Http_Client instance is shared among all Zend_Service_Abstract subclasses.
      */
     $this->_localHttpClient->resetParameters()->setUri($this->_uri);
 }
コード例 #21
0
	public function getCataIds($sDir){
		print_r('<h3>OutPut CSV</h3>');
		
		//solr connection
		//echo phpInfo();
		
		
		$prodCol=Mage::getModel('catalog/product')->getCollection();
		$prodCol->addAttributeToSelect('*');
		echo "<hr/>";
		foreach($prodCol as $p1){			
			$cata1=$p1->getCategoryIds();
			$tOut['id']=$p1->getId();
					
			$cOut="";
			foreach($cata1 as $cata){
				$_cat=Mage::getModel('catalog/category')->load($cata);
				$cOut=$cOut.$_cat->getName()." ";
			}
			rtrim($cOut,',');
			$tOut['cat']=str_replace('+','',$cOut);
			$tOut['sku']=$p1->getSku();
			$nameTemp = strip_tags($p1->getName());
			$nameTemp = str_replace('&mdash; ','',$nameTemp);
			$tOut['name']=strip_tags($nameTemp);
			$tOut['manu']=$p1->getAttributeText('manufacturer');
			$tOut['url']=$p1->getProductUrl();
			$tOut['features']=strip_tags($p1->getShortDescription());
			$tOut1['doc']=$tOut;
			$tOut2['add']=$tOut1;
			$jOut=$jOut.json_encode($tOut2);
		}
		//echo $jOut;
		echo '<br/><br/>';
		echo "<hr/>";
		
		$url='http://65.60.97.68:8983/solr/'.$sDir.'/update/json?commit=true';
		$Client = new Zend_Http_Client($url);
		$Client->resetParameters();
		$Client->setMethod(Zend_Http_Client::POST);
		$Client->setHeaders('Content-type','application/json');
		$Client->setRawData($jOut);
		$response=$Client->request();
		echo $response.'<hr/>';
	
	}
コード例 #22
0
ファイル: Facebook.php プロジェクト: omusico/logica
 /**
  * Convenience method to run the command
  *
  * @param string $name
  * @param mixed $args
  * @return boolean
  */
 public function onCommand($name, $args)
 {
     if (strcasecmp($name, $this->_commandName) !== 0) {
         return FALSE;
     }
     //Do the command
     if (count($args) && (Zend_Registry::get('IS_PRODUCTION') || App_DI_Container::get('ConfigObject')->facebook->testing)) {
         $args['access_token'] = App_DI_Container::get('ConfigObject')->facebook->access_token;
         $url = 'https://graph.facebook.com/YOUR_PAGE/feed';
         $client = new Zend_Http_Client($url);
         $client->setMethod(Zend_Http_Client::POST);
         $client->resetParameters();
         $client->setParameterPost($args);
         $response = $client->request();
         return $response->isSuccessful();
     }
     return FALSE;
 }
コード例 #23
0
 /**
  * Run the crawler until we hit the last URL
  *
  * @param string $url URL to start crawling from
  */
 public function run($url)
 {
     if (!Zend_Uri_Http::check($url)) {
         require_once 'Spizer/Exception.php';
         throw new Spizer_Exception("'{$url}' is not a valid HTTP URI");
     }
     $this->_baseUri = Zend_Uri::factory($url);
     $this->_queue->append($url);
     // Set the default logger if not already set
     if (!$this->logger) {
         require_once 'Spizer/Logger/Xml.php';
         $this->logger = new Spizer_Logger_Xml();
     }
     // Go!
     while ($request = $this->_queue->next()) {
         $this->logger->startPage();
         $this->logger->logRequest($request);
         // Prepare HTTP client for next request
         $this->_httpClient->resetParameters();
         $this->_httpClient->setUri($request->getUri());
         $this->_httpClient->setMethod($request->getMethod());
         $this->_httpClient->setHeaders($request->getAllHeaders());
         $this->_httpClient->setRawData($request->getBody());
         // Send request, catching any HTTP related issues that might happen
         try {
             $response = new Spizer_Response($this->_httpClient->request());
         } catch (Zend_Exception $e) {
             fwrite(STDERR, "Error executing request: {$e->getMessage()}.\n");
             fwrite(STDERR, "Request information:\n");
             fwrite(STDERR, "  {$request->getMethod()} {$request->getUri()}\n");
             fwrite(STDERR, "  Referred by: {$request->getReferrer()}\n");
         }
         $this->logger->logResponse($response);
         // Call handlers
         $this->_callHandlers($request, $response);
         // End page
         $this->logger->endPage();
         ++$this->_requestCounter;
         // Wait if a delay was set
         if (isset($this->_config['delay'])) {
             sleep($this->_config['delay']);
         }
     }
 }
コード例 #24
0
 /**
  * Performs an HTTP GET request to the $path.
  *
  * @param string $path
  * @param array  $query Array of GET parameters
  * @throws Zend_Http_Client_Exception
  * @return Zend_Http_Response
  */
 protected function _getResponse($path, array $query = null)
 {
     // Get the URI object and configure it
     if (!$this->_uri instanceof Zend_Uri_Http) {
         require_once 'Zend/Rest/Client/Exception.php';
         throw new Zend_Rest_Client_Exception('URI object must be set before performing call');
     }
     $uri = $this->_uri->getUri();
     if ($path[0] != '/') {
         $path = '/' . $path;
     }
     $this->_uri->setPath($path);
     /**
      * Get the HTTP client and configure it for the endpoint URI.  Do this each time
      * because the Zend_Http_Client instance is shared among all Zend_Service_Abstract subclasses.
      */
     $this->_localHttpClient->resetParameters()->setUri($this->_uri)->setParameterGet($query);
     return $this->_localHttpClient->request('GET');
 }
コード例 #25
0
 /**
  * Handles all GET requests to a web service
  *
  * @param string $path Path
  * @param array $parms Array of GET parameters
  * @param string $type Type of a request xml|json
  * @return DOMDocument response from web service
  */
 public function makeRequest($path, $parms = array(), $type = 'xml')
 {
     settype($parms, 'array');
     // if previous request was made less then 1 sec ago
     // wait until we can make a new request
     $timeDiff = microtime(true) - self::$_lastRequestTime;
     if ($timeDiff < 1) {
         usleep((1 - $timeDiff) * 1000000);
     }
     $this->_http->resetParameters();
     foreach ($parms as $f_parm => $f_value) {
         $this->_http->setParameterGet($f_parm, $f_value);
     }
     switch ($type) {
         case 'xml':
             $this->_http->setUri(self::API_URI . $path);
             break;
         case 'json':
             $this->_http->setUri(self::JSON_URI . $path);
             $this->_http->setParameterGet('raw', true);
             break;
         default:
             throw new Zend_Service_Delicious_Exception('Unknown request type');
     }
     self::$_lastRequestTime = microtime(true);
     $response = $this->_http->request(Zend_Http_Client::GET);
     if (!$response->isSuccessful()) {
         throw new Zend_Service_Delicious_Exception("Http client reported an error: '{$response->getMessage()}'");
     }
     $responseBody = $response->getBody();
     switch ($type) {
         case 'xml':
             $dom = new DOMDocument();
             if (!@$dom->loadXML($responseBody)) {
                 throw new Zend_Service_Delicious_Exception('XML Error');
             }
             return $dom;
         case 'json':
             return Zend_Json::decode($responseBody);
     }
 }
コード例 #26
0
 /**
  * Return a single record
  *
  * @param string $_id
  * @param $_getDeleted get deleted records
  * @return Tinebase_Record_Interface
  */
 public function get($_id, $_getDeleted = FALSE)
 {
     // get basics
     $this->_httpClient->resetParameters();
     $this->_httpClient->setUri($this->_config->rest->url . "/REST/1.0/ticket/" . $_id . "/show");
     $this->_httpClient->setMethod(Zend_Http_Client::GET);
     $response = $this->_httpClient->request();
     $ticket = $this->_rawDataToTicket($response->getBody());
     // get history
     $this->_httpClient->resetParameters();
     $this->_httpClient->setUri($this->_config->rest->url . "/REST/1.0/ticket/" . $_id . "/history");
     $this->_httpClient->setParameterGet('format', 'l');
     $this->_httpClient->setMethod(Zend_Http_Client::GET);
     $response = $this->_httpClient->request();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__FILE__ . '::' . __LINE__ . ' request :' . $this->_httpClient->getLastRequest());
     }
     //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__FILE__ . '::' . __LINE__ . ' response :' . $response->asString());
     $ticket->History = $this->_rawDataToHistory($response->getBody());
     return $ticket;
 }
コード例 #27
0
 /**
  * Send an email using the amazon webservice api
  *
  * @return void
  */
 public function _sendMail()
 {
     //Send the request
     $client = new Zend_Http_Client($this->_host . '/api/mail.send.json');
     $client->setMethod(Zend_Http_Client::POST);
     $recipients = explode(',', $this->recipients);
     foreach ($this->_mail->getRecipients() as $recipient) {
         $client->resetParameters();
         $params = array('api_user' => $this->_api_username, 'api_key' => $this->_api_password, 'subject' => $this->_mail->getSubject(), 'html' => $this->_mail->getBodyHtml()->getRawContent(), 'text' => $this->_mail->getBodyText()->getRawContent(), 'from' => $this->_mail->getFrom(), 'to' => $recipient);
         $client->setParameterPost($params);
         $response = $client->request(Zend_Http_Client::POST);
         $json = Zend_Json::decode($response->getBody());
         if ($response->getStatus() != 200 || $json['message'] == 'error') {
             /**
              * @see Zend_Mail_Transport_Exception
              */
             require_once 'Zend/Mail/Transport/Exception.php';
             throw new Zend_Mail_Transport_Exception('Unable to send mail - ' . $json['errors'][0]);
         }
     }
 }
コード例 #28
0
ファイル: AmazonSES.php プロジェクト: avramishin/pinwall
 /**
  * Send an email using the amazon webservice api
  *
  * @return void
  */
 public function _sendMail()
 {
     $date = gmdate('D, d M Y H:i:s O');
     //Send the request
     $client = new Zend_Http_Client($this->_host);
     $client->setMethod(Zend_Http_Client::POST);
     $client->setHeaders(array('Date' => $date, 'X-Amzn-Authorization' => $this->_buildAuthKey($date)));
     //Build the parameters
     $params = array('Action' => 'SendRawEmail', 'Source' => $this->_mail->getFrom(), 'RawMessage.Data' => base64_encode(sprintf("%s\n%s\n", $this->header, $this->body)));
     $recipients = explode(',', $this->recipients);
     while (list($index, $recipient) = each($recipients)) {
         $params[sprintf('Destination.ToAddresses.member.%d', $index + 1)] = $recipient;
     }
     $client->resetParameters();
     $client->setEncType(Zend_Http_Client::ENC_URLENCODED);
     $client->setParameterPost($params);
     $response = $client->request(Zend_Http_Client::POST);
     if ($response->getStatus() != 200) {
         throw new Exception($response->getBody());
     }
 }
コード例 #29
0
ファイル: Api.php プロジェクト: recensus/php-sdk
 /**
  * Makes a request to the Recensus API.
  * 
  * @return boolean
  */
 protected function makeRequest($url, $method, $data = null)
 {
     // If the SDK is used multiple times ensure all params are reset.
     $this->httpClient->resetParameters(true);
     $this->httpClient->setHeaders('Accept', 'applicaton/json');
     $this->httpClient->setMethod($method);
     $this->httpClient->setUri($url);
     if (!is_null($data)) {
         $formattedRequest = array('data' => $data, 'signedRequest' => $this->signRequest($method, $url));
         $jsonEncodedData = json_encode($formattedRequest);
         if (!$jsonEncodedData) {
             $this->handleError("Error json encoding before sending request");
         }
         // Content-Type must be sent or 500 returned
         $this->httpClient->setHeaders('Content-Type', 'application/json');
         $this->httpClient->setRawData($jsonEncodedData);
     }
     try {
         $this->lastResponse = $this->httpClient->request();
     } catch (Exception $e) {
         $this->handleError($e->getMessage());
     }
 }
コード例 #30
0
 /**
  *
  * @param  string                   $rulesetName
  * @param  array                    $params
  * @return array                    Result of the validation
  * @throws TidJS_Validate_Exception If there was a problem
  */
 public function validate($rulesetName, $params)
 {
     $this->_hasErrors = false;
     if (empty($this->_url)) {
         throw new App_Controller_Action_Helper_Validate_Exception('Error using NodeRunner: empty URL');
     }
     try {
         $this->_client->setUri($this->_url . '/' . $rulesetName);
         $this->_client->resetParameters();
         foreach ($params as $k => $v) {
             $this->_client->setParameterGet($k, $v);
         }
         // Pass the evaled code as an argument
         $this->_client->setParameterGet('__assigns__', json_encode($this->_assigns));
         $response = $this->_client->request('GET');
         $code = $response->getStatus();
         $body = $response->getBody();
         if ($code < 200 || $code >= 400) {
             throw new App_Controller_Action_Helper_Validate_Exception('Validation service returned an unexpected error: ' . $body, $code);
         }
         $result = json_decode($body, true);
         if (empty($result)) {
             throw new App_Controller_Action_Helper_Validate_Exception('Validation service returned invalid JSON data: ' . $body);
         }
         // Loop over all the fields returned
         foreach ($result as $k => $v) {
             // Check if we found an error
             if (is_array($v) && !empty($v['_validate_error'])) {
                 $this->_hasErrors = true;
                 $result[$k] = new App_Controller_Action_Helper_Validate_Error($v['message'], $v['params']);
             }
         }
     } catch (Exception $e) {
         throw new App_Controller_Action_Helper_Validate_Exception('Error using NodeRunner: ' . $e->getMessage());
     }
     return $result;
 }