setRawData() public method

This function is here for two reasons: 1. For advanced user who would like to set their own data, already encoded 2. For backwards compatibilty: If someone uses the old post($data) method. this method will be used to set the encoded data. $data can also be stream (such as file) from which the data will be read.
public setRawData ( string | resource $data, string $enctype = null ) : Zend_Http_Client
$data string | resource
$enctype string
return Zend_Http_Client
Exemplo n.º 1
0
 public function sayRoom($room, $message, $type = 'TextMessage')
 {
     $uri = 'https://' . $this->subdomain . '.campfirenow.com/room/' . $room . '/speak.json';
     $this->client->setUri($uri);
     $params['message']['type'] = $type;
     $params['message']['body'] = $message;
     $this->client->setHeaders('Content-type', 'application/json');
     $this->client->setRawData(json_encode($params));
     $this->client->setMethod(Zend_Http_Client::POST);
     $response = $this->client->request();
     return (bool) ($response->getStatus() == 200);
 }
 public function doRequest($url, $params = array())
 {
     $client = new Zend_Http_Client(trim($url), array());
     if (array_key_exists('raw', $params)) {
         $client->setRawData(json_encode($params['raw']), 'application/json');
     } else {
         $client->setParameterPost($params);
     }
     if (extension_loaded('curl')) {
         $adapter = new Zend_Http_Client_Adapter_Curl();
         $adapter->setCurlOption(CURLOPT_SSL_VERIFYPEER, true);
         $adapter->setCurlOption(CURLOPT_SSL_VERIFYHOST, 2);
         $client->setAdapter($adapter);
     }
     $response = $client->request('POST');
     $res = $response->getBody();
     if ($response->isError()) {
         $this->log("Request fail. Http code : " . $response->getStatus() . ' Message : ' . $res, 'ERROR');
         $this->log("Request data : " . print_r($params, 1), 'ERROR');
         if (array_key_exists('raw', $params)) {
             return $response;
         }
     }
     if (array_key_exists('raw', $params)) {
         return json_decode($res, true);
     }
     $result = null;
     parse_str($res, $result);
     return $result;
 }
Exemplo n.º 3
0
	/**
	 * Test using raw HTTP POST data
	 *
	 */
	public function testRawPostData() 
	{
		$data = "Chuck Norris never wet his bed as a child. The bed wet itself out of fear.";
		
		$res = $this->client->setRawData($data, 'text/html')->request('POST');
		$this->assertEquals($data, $res->getBody(), 'Response body does not contain the expected data');
	}
Exemplo n.º 4
0
 /**
  * POST xml data to Google with authorization headers set
  *
  * @param string $xml
  * @param string $uri POST URI
  * @return Zend_Http_Response
  */
 public function post($xml, $uri = null)
 {
     if ($uri == null) {
         $uri = $this->_defaultPostUri;
     }
     if ($uri == null) {
         throw Zend::exception('Zend_Gdata_Exception', 'You must specify an URI to which to post.');
     }
     $this->_httpClient->setUri($uri);
     $this->_httpClient->setConfig(array('maxredirects' => 0));
     $this->_httpClient->setRawData($xml, 'application/atom+xml');
     $response = $this->_httpClient->request('POST');
     //set "S" cookie to avoid future redirects.
     if ($cookie = $response->getHeader('Set-cookie')) {
         list($cookieName, $cookieValue) = explode('=', $cookie, 2);
         $this->_httpClient->setCookie($cookieName, $cookieValue);
     }
     if ($response->isRedirect()) {
         //this usually happens. Re-POST with redirected URI.
         $this->_httpClient->setUri($response->getHeader('Location'));
         $this->_httpClient->setRawData($xml, 'application/atom+xml');
         $response = $this->_httpClient->request('POST');
     }
     if (!$response->isSuccessful()) {
         throw Zend::exception('Zend_Gdata_Exception', 'Post to Google failed.');
     }
     return $response;
 }
Exemplo n.º 5
0
 protected function _api_request($method, $path, $data = null)
 {
     $url = trim($this->getBaseApiUrl(), "/") . self::API_CHECKOUT_PATH . $path;
     $client = new Zend_Http_Client($url);
     if (in_array($method, array(Zend_Http_Client::POST, Zend_Http_Client::PUT, 'PATCH')) && $data) {
         $client->setHeaders('Content-type: application/json');
         $client->setRawData(json_encode($data), 'application/json');
     }
     $client->setHeaders('Authorization: Bearer ' . Mage::getStoreConfig('payment/aplazame/secret_api_key'));
     $client->setHeaders('User-Agent: ' . self::USER_AGENT);
     $client->setHeaders('Accept: ' . 'application/vnd.aplazame' . (Mage::getStoreConfig('payment/aplazame/sandbox') ? '.sandbox-' : '-') . Mage::getStoreConfig('payment/aplazame/version') . '+json');
     $response = $client->request($method);
     $raw_result = $response->getBody();
     $status_code = $response->getStatus();
     if ($status_code >= 500) {
         Mage::throwException(Mage::helper('aplazame')->__('Aplazame error code: ' . $status_code));
     }
     try {
         $ret_json = Zend_Json::decode($raw_result, Zend_Json::TYPE_ARRAY);
     } catch (Zend_Json_Exception $e) {
         Mage::throwException(Mage::helper('aplazame')->__('Invalid api response: ' . $raw_result));
     }
     if ($status_code >= 400) {
         Mage::throwException(Mage::helper('aplazame')->__('Aplazame error code ' . $status_code . ': ' . $ret_json['error']['message']));
     }
     return $ret_json;
 }
Exemplo n.º 6
0
 /**
  * @param \ShipperHQ\WS\WebServiceRequest $requestObj
  * @param $webServicePath
  * @return mixed|null
  */
 public function sendAndReceive(WebServiceRequestInterface $requestObj, $webServiceURL, $timeout = 30)
 {
     $jsonRequest = json_encode($requestObj);
     $debugRequest = $requestObj;
     $debugRequest->credentials->password = null;
     $jsonDebugRequest = json_encode($debugRequest, JSON_PRETTY_PRINT);
     $debugData['json_request'] = $jsonDebugRequest;
     $debugData['url'] = $webServiceURL;
     $responseBody = '';
     try {
         $client = new \Zend_Http_Client();
         $client->setUri($webServiceURL);
         $client->setConfig(['maxredirects' => 0, 'timeout' => $timeout]);
         $client->setRawData($jsonRequest, 'application/json');
         $response = $client->request(\Zend_Http_Client::POST);
         if (!is_null($response)) {
             $responseBody = $response->getBody();
         }
         $debugData['response'] = $responseBody;
         $responseBody = json_decode($responseBody, false);
     } catch (\Exception $e) {
         $debugData['error'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
         $debugData['response'] = '';
     }
     $result = ['result' => $responseBody, 'debug' => $debugData];
     return $result;
 }
Exemplo n.º 7
0
 /**
  * CLI Bot action
  * 
  */
 public function botAction()
 {
     // Retrieve configuration
     $config = Zend_Registry::get('config');
     // URI to be called
     $uri = $config->snsServerUrlScheme . '://' . $config->snsServerUrlHost . $config->snsServerUrlPath . 'default/wikiarticle/create';
     try {
         // Connect to POP3 mail storage
         $mail = new Zend_Mail_Storage_Pop3(array('host' => $config->wikiarticle->pop3->host, 'port' => $config->wikiarticle->pop3->port, 'user' => $config->wikiarticle->pop3->user, 'password' => $config->wikiarticle->pop3->pass));
     } catch (Exception $ex) {
         //SWAT_Log::get()->MailPuller()->err($ex->getMessage());
         Zend_Registry::get('log')->err($ex->getMessage());
     }
     // Generate mail puller instance
     $puller = new SWAT_Mail_Puller();
     $puller->setFileDir(sys_get_temp_dir());
     $puller->setFileTypes(array_map('trim', explode(',', $config->wikiarticleAllowedMimeTypes)));
     //echo 'We have ' . $mail->countMessages() . ' messages to process.<br />';
     //echo 'Attachments will be stored in directory: ' . sys_get_temp_dir() . '<br />';
     // Foreach mail found
     foreach ($mail as $number => $message) {
         //echo 'Found message with title: ' . $message->subject . '<br />';
         // Check if it's a wiki article to be created
         if (strtoupper(substr($message->subject, 0, 5)) === 'WIKI:') {
             try {
                 // Retrieve message information
                 $info = $puller->getMessageInfo($message);
                 // Post found information to wiki article creator
                 $client = new Zend_Http_Client($uri);
                 $client->setRawData(Zend_Json::encode($info));
                 $response = $client->request(Zend_Http_Client::POST);
                 //echo 'Response: <pre>' . var_export($response->getBody(), true) . '</pre>';
                 // Switch to each response status
                 switch ($response->getStatus()) {
                     case 400:
                         throw new Exception('Invalid request.');
                         break;
                     case 500:
                         throw new Exception('Internal server error.');
                         break;
                     default:
                         // Decode response
                         $body = SWAT_Encoder::decode($response->getRawBody());
                         // If error code is not 201, we need to report the issue
                         if ($body['code'] != 201) {
                             throw new Exception($body['message']);
                         }
                         // Generate log entry
                         //SWAT_Log::get()->MailPuller()->debug($body['message']);
                         Zend_Registry::get('log')->debug($body['message']);
                         break;
                 }
             } catch (Exception $ex) {
                 //SWAT_Log::get()->MailPuller()->err($ex->getMessage());
                 Zend_Registry::get('log')->err($ex->getMessage());
             }
         }
         $mail->noop();
     }
 }
Exemplo n.º 8
0
 protected function _call($endpoint, $params = null, $method = 'GET', $data = null)
 {
     if ($params && is_array($params) && count($params) > 0) {
         $args = array();
         foreach ($params as $arg => $val) {
             $args[] = urlencode($arg) . '=' . urlencode($val);
         }
         $endpoint .= '?' . implode('&', $args);
     }
     $url = $this->_getUrl($endpoint);
     $method = strtoupper($method);
     $client = new Zend_Http_Client($url);
     $client->setMethod($method);
     $client->setHeaders(array('Accept' => 'application/json', 'Content-Type' => 'application/json'));
     $client->setAuth(Mage::getStoreConfig('zendesk/general/email') . '/token', Mage::getStoreConfig('zendesk/general/password'));
     if ($method == 'POST') {
         $client->setRawData(json_encode($data), 'application/json');
     }
     Mage::log(print_r(array('url' => $url, 'method' => $method, 'data' => json_encode($data)), true), null, 'zendesk.log');
     $response = $client->request();
     $body = json_decode($response->getBody(), true);
     Mage::log(var_export($body, true), null, 'zendesk.log');
     if ($response->isError()) {
         if (is_array($body) && isset($body['error'])) {
             if (is_array($body['error']) && isset($body['error']['title'])) {
                 throw new Exception($body['error']['title'], $response->getStatus());
             } else {
                 throw new Exception($body['error'], $response->getStatus());
             }
         } else {
             throw new Exception($body, $response->getStatus());
         }
     }
     return $body;
 }
Exemplo n.º 9
0
 public function testPut($record, $id, $format = 'xml')
 {
     $client = new \Zend_Http_Client(REST_URL_PUT . '/' . $id . '?format=' . $format);
     $client->setRawData(json_encode($record));
     $response = $client->request('PUT');
     print $response->getBody();
 }
Exemplo n.º 10
0
 /**
  * 
  */
 protected function _request($url, $params, $method = Zend_Http_Client::GET)
 {
     $this->_client->setUri($url)->resetParameters();
     if (count($params['header'])) {
         foreach ($params['header'] as $name => $value) {
             $this->_client->setHeaders($name, $value);
         }
     }
     if (count($params['post'])) {
         foreach ($params['post'] as $name => $value) {
             $this->_client->setParameterPost($name, $value);
         }
     }
     if (count($params['get'])) {
         foreach ($params['get'] as $name => $value) {
             $this->_client->setParameterGet($name, $value);
         }
     }
     if (count($params['json'])) {
         //$this->_client->setHeaders('Content-type','application/json');
         $rawJson = json_encode($params['json']);
         //$this->_client->setRawData($rawJson);
         $this->_client->setRawData($rawJson, 'application/json');
     }
     $response = $this->_client->request($method);
     $result = $response->getBody();
     #echo $result . "\n\n <br>";
     return json_decode($result);
 }
 protected function execute($arguments = array(), $options = array())
 {
     require_once realpath(dirname(__FILE__) . '/../../../../lib/vendor/OAuth/OAuth.php');
     new sfDatabaseManager($this->configuration);
     sfContext::createInstance($this->createConfiguration('pc_frontend', 'prod'), 'pc_frontend');
     $consumerKey = isset($options['consumer-key']) && $options['consumer-key'] ? $options['consumer-key'] : opOpenSocialToolKit::getOAuthConsumerKey();
     $consumer = new OAuthConsumer($consumerKey, null, null);
     $signatureMethod = new OAuthSignatureMethod_RSA_SHA1_opOpenSocialPlugin();
     $httpOptions = opOpenSocialToolKit::getHttpOptions();
     $queueGroups = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueueGroups();
     $limitRequest = (int) $options['limit-request'];
     $limitRequestApp = (int) $options['limit-request-app'];
     $allRequest = 0;
     foreach ($queueGroups as $group) {
         $application = Doctrine::getTable('Application')->find($group[0]);
         $links = $application->getLinks();
         $linkHash = array();
         foreach ($links as $link) {
             if (isset($link['rel']) && isset($link['href'])) {
                 $method = isset($link['method']) ? strtolower($link['method']) : '';
                 $method = 'post' !== $method ? 'get' : 'post';
                 $linkHash[$link['rel']] = array('href' => $link['href'], 'method' => $method);
             }
         }
         $queues = Doctrine::getTable('ApplicationLifecycleEventQueue')->getQueuesByApplicationId($group[0], $limitRequestApp);
         foreach ($queues as $queue) {
             if (!isset($linkHash[$queue->getName()])) {
                 $queue->delete();
                 continue;
             }
             $href = $linkHash[$queue->getName()]['href'];
             $method = $linkHash[$queue->getName()]['method'];
             $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, $method, $href, $queue->getParams());
             $oauthRequest->sign_request($signatureMethod, $consumer, null);
             $client = new Zend_Http_Client();
             if ('post' !== $method) {
                 $method = 'get';
                 $client->setMethod(Zend_Http_Client::GET);
                 $href .= '?' . $oauthRequest->to_postdata();
             } else {
                 $client->setMethod(Zend_Http_Client::POST);
                 $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED);
                 $client->setRawData($oauthRequest->to_postdata());
             }
             $client->setConfig($httpOptions);
             $client->setUri($href);
             $client->setHeaders($oauthRequest->to_header());
             $response = $client->request();
             if ($response->isSuccessful()) {
                 $queue->delete();
             }
             $allRequest++;
             if ($limitRequest && $limitRequest <= $allRequest) {
                 break 2;
             }
         }
         $application->free(true);
         $queues->free(true);
     }
 }
Exemplo n.º 12
0
 protected function sendRequest($accountId, $accessToken, $body)
 {
     $client = new Zend_Http_Client();
     $client->setUri("https://api.edgecast.com/v2/mcc/customers/{$accountId}/edge/purge");
     $client->setHeaders(array('Authorization' => "TOK:{$accessToken}", 'Content-Type' => 'application/json'));
     $client->setRawData(json_encode($body));
     return $client->request(Zend_Http_Client::PUT);
 }
 public function fetchRequest(RemoteContentRequest $request)
 {
     $outHeaders = array();
     if ($request->hasHeaders()) {
         $headers = explode("\n", $request->getHeaders());
         foreach ($headers as $header) {
             if (strpos($header, ':')) {
                 $key = trim(substr($header, 0, strpos($header, ':')));
                 $val = trim(substr($header, strpos($header, ':') + 1));
                 if (strcmp($key, "User-Agent") != 0 && strcasecmp($key, "Transfer-Encoding") != 0 && strcasecmp($key, "Cache-Control") != 0 && strcasecmp($key, "Expries") != 0 && strcasecmp($key, "Content-Length") != 0) {
                     $outHeaders[$key] = $val;
                 }
             }
         }
     }
     $outHeaders['User-Agent'] = "Shindig PHP";
     $options = array();
     $options['timeout'] = Shindig_Config::get('curl_connection_timeout');
     // configure proxy
     $proxyUrl = Shindig_Config::get('proxy');
     if (!empty($proxyUrl)) {
         $options['adapter'] = 'Zend_Http_Client_Adapter_Proxy';
         $proxy = parse_url($proxyUrl);
         if (isset($proxy['host'])) {
             $options['proxy_host'] = $proxy['host'];
         }
         if (isset($proxy['port'])) {
             $options['proxy_port'] = $proxy['port'];
         }
         if (isset($proxy['user'])) {
             $options['proxy_user'] = $proxy['user'];
         }
         if (isset($proxy['pass'])) {
             $options['proxy_pass'] = $proxy['pass'];
         }
     }
     $client = new Zend_Http_Client();
     $client->setConfig($options);
     $client->setUri($request->getUrl());
     $client->setHeaders($outHeaders);
     if ($request->getContentType()) {
         $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, $request->getContentType());
     }
     if ($request->isPost()) {
         $client->setMethod(Zend_Http_Client::POST);
         $client->setRawData($request->getPostBody());
     } else {
         $client->setMethod(Zend_Http_Client::GET);
     }
     $response = $client->request();
     $request->setHttpCode($response->getStatus());
     $request->setContentType($response->getHeader('Content-Type'));
     $request->setResponseHeaders($response->getHeaders());
     $request->setResponseContent($response->getBody());
     $request->setResponseSize(strlen($response->getBody()));
     return $request;
 }
Exemplo n.º 14
0
 public function saveMetaDataForDocument($id, $data)
 {
     $config = Zend_Registry::getInstance()->config->watson;
     $this->_httpClient->setUri($config->saveMetaDataUrl . $id);
     $this->_httpClient->setHeaders(array('X-SyncTimeout' => $config->timeout, 'Content-Type' => 'application/json', 'Accept' => 'application/json'));
     $response = $this->_httpClient->setRawData($data)->request(Zend_Http_Client::PUT);
     $responseBody = Zend_Json::decode($response->getBody());
     return $responseBody;
 }
Exemplo n.º 15
0
 public function set($graph, $turtle)
 {
     $client = new Zend_Http_Client();
     $client->setUri($this->_endpoint . $graph);
     $client->setHeaders('Content-Type', 'application/x-turtle');
     $client->setRawData(FourStore_Namespace::to_turtle() . $turtle);
     $response = $client->request('PUT');
     return $response;
 }
Exemplo n.º 16
0
 public static function getClient(Sitengine_Amazon_S3_Header $header, $body = '')
 {
     require_once 'Zend/Http/Client.php';
     $client = new Zend_Http_Client($header->getUrl());
     $client->setRawData($body);
     foreach ($header->toArray() as $h) {
         $client->setHeaders($h);
     }
     return $client;
 }
Exemplo n.º 17
0
 /**
  * POST data to Google with authorization headers set
  *
  * @param mixed $data The Zend_Gdata_App_Entry or XML to post
  * @param string $uri POST URI
  * @return Zend_Http_Response
  * @throws Zend_Gdata_App_Exception
  * @throws Zend_Gdata_App_HttpException
  * @throws Zend_Gdata_App_InvalidArgumentException
  */
 public function post($data, $uri = null)
 {
     require_once 'Zend/Http/Client/Exception.php';
     if (is_string($data)) {
         $rawData = $data;
     } elseif ($data instanceof Zend_Gdata_App_Entry) {
         $rawData = $data->saveXML();
     } 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) {
         $uri = $this->_defaultPostUri;
     }
     if ($uri == null) {
         require_once 'Zend/Gdata/App/InvalidArgumentException.php';
         throw new Zend_Gdata_App_InvalidArgumentException('You must specify an URI to which to post.');
     }
     $this->_httpClient->setUri($uri);
     $this->_httpClient->setConfig(array('maxredirects' => 0));
     $this->_httpClient->setRawData($rawData, 'application/atom+xml');
     try {
         $response = $this->_httpClient->request('POST');
     } catch (Zend_Http_Client_Exception $e) {
         require_once 'Zend/Gdata/App/HttpException.php';
         throw new Zend_Gdata_App_HttpException($e->getMessage(), $e);
     }
     /**
      * set "S" cookie to avoid future redirects.
      */
     if ($cookie = $response->getHeader('Set-cookie')) {
         list($cookieName, $cookieValue) = explode('=', $cookie, 2);
         $this->_httpClient->setCookie($cookieName, $cookieValue);
     }
     if ($response->isRedirect()) {
         /**
          * Re-POST with redirected URI.
          * This happens frequently.
          */
         $this->_httpClient->setUri($response->getHeader('Location'));
         $this->_httpClient->setRawData($rawData, 'application/atom+xml');
         try {
             $response = $this->_httpClient->request('POST');
         } catch (Zend_Http_Client_Exception $e) {
             throw new Zend_Gdata_App_HttpException($e->getMessage(), $e);
         }
     }
     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;
 }
Exemplo n.º 18
0
 /**
  * Sendet den übergebenen Request zum Server und gibt das Result zurück
  * @param Dragon_Json_Server_Request_Http $request
  * @return array
  */
 public function send(Dragon_Json_Server_Request_Http $request)
 {
     $request->addParam(-1, 'timestamp');
     $body = $this->_httpclient->setRawData($request->toJson())->request('POST')->getBody();
     try {
         $response = Zend_Json::decode($body);
     } catch (Exception $exception) {
         throw new Dragon_Application_Exception_System('decoding failed', array('message' => $exception->getMessage(), 'body' => $body));
     }
     if (!is_array($response) || !array_key_exists('id', $response)) {
         throw new Dragon_Application_Exception_System('invalid response', array('response' => $response, 'body' => $body));
     }
     if (array_key_exists('error', $response)) {
         throw new Dragon_Application_Exception_System($response['error']['message'], array('error' => $response['error']));
     }
     if (!array_key_exists('result', $response)) {
         throw new Dragon_Application_Exception_System('invalid response', array('response' => $response, 'body' => $body));
     }
     return $response['result'];
 }
 /**
  * @group ZF-10645
  */
 public function testPutRequestsHonorSpecifiedContentType()
 {
     $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
     $this->client->setMethod(Zend_Http_Client::PUT);
     $data = array('foo' => 'bar');
     $this->client->setRawData(http_build_query($data), 'text/html; charset=ISO-8859-1');
     $response = $this->client->request();
     $request = $this->client->getLastRequest();
     $this->assertContains('text/html; charset=ISO-8859-1', $request, $request);
     $this->assertContains('REQUEST_METHOD: PUT', $response->getBody(), $response->getBody());
 }
Exemplo n.º 20
0
 /**
  * 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;
 }
Exemplo n.º 21
0
 public function testStreamRequest()
 {
     if (!$this->client->getAdapter() instanceof Adapter\Stream) {
         $this->markTestSkipped('Current adapter does not support streaming');
         return;
     }
     $data = fopen(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'staticFile.jpg', "r");
     $res = $this->client->setRawData($data, 'image/jpeg')->request('PUT');
     $expected = $this->_getTestFileContents('staticFile.jpg');
     $this->assertEquals($expected, $res->getBody(), 'Response body does not contain the expected data');
 }
Exemplo n.º 22
0
 function postText($analysisMethod = 1)
 {
     $client = new Zend_Http_Client(self::APIuri, array('timeout' => 120));
     $client->setHeaders('Accept', 'application/json');
     $client->setHeaders('Content-Type', $this->contentType);
     $client->setHeaders('x-geoNER-alg', $analysisMethod);
     $client->setHeaders('x-geoNER-yahooKey', self::YahooAPIkey);
     //$client->setParameterPost('data', $this->text);
     $client->setRawData($this->text);
     @($response = $client->request("POST"));
     return $response;
 }
Exemplo n.º 23
0
 /**
  * Test that we properly calculate the content-length of multibyte-encoded
  * request body
  *
  * This may file in case that mbstring overloads the substr and strlen
  * functions, and the mbstring internal encoding is a multibyte encoding.
  *
  * @link http://framework.zend.com/issues/browse/ZF-2098
  */
 public function testMultibyteRawPostDataZF2098()
 {
     $this->_client->setAdapter('Zend_Http_Client_Adapter_Test');
     $this->_client->setUri('http://example.com');
     $bodyFile = dirname(__FILE__) . '/_files/ZF2098-multibytepostdata.txt';
     $this->_client->setRawData(file_get_contents($bodyFile), 'text/plain');
     $this->_client->request('POST');
     $request = $this->_client->getLastRequest();
     if (!preg_match('/^content-length:\\s+(\\d+)/mi', $request, $match)) {
         $this->fail("Unable to find content-length header in request");
     }
     $this->assertEquals(filesize($bodyFile), (int) $match[1]);
 }
Exemplo n.º 24
0
 /**
  * @param  array               $data
  * @return \Zend_Http_Response
  */
 private function submitData(array $data)
 {
     $dataString = json_encode($data);
     $encryptionMethod = 'aes128';
     if ($this->isEncryptionSupported($encryptionMethod)) {
         $data = $this->encryptData($dataString, $encryptionMethod);
         $dataString = json_encode($data);
     }
     $apiUrl = $this->apiEndpoint . '/submission';
     $client = new \Zend_Http_Client($apiUrl, array('timeout' => 1, 'useragent' => 'Shopware/' . \Shopware::VERSION));
     $response = $client->setRawData($dataString)->setEncType('application/json')->request('POST');
     return $response;
 }
Exemplo n.º 25
0
 /**
  * Определение речи во входном файле
  * пока корректно определяется только mp3
  * @param string $input
  * @param string $lang
  */
 public static function speechToText($input, $lang = 'ru-RU')
 {
     $file = self::_toFlac($input);
     $clinet = new Zend_Http_Client(self::$speechToTextUrl);
     $clinet->setParameterGet(array('xjerr' => '1', 'client' => 'chromium', 'lang' => $lang));
     $sampleRate = self::_getFileInfo($file, 'SampleRate');
     $clinet->setRawData(file_get_contents($file), 'audio/x-flac; rate=' . $sampleRate);
     $response = $clinet->request('POST');
     unlink($file);
     if (200 == $response->getStatus()) {
         return Zend_Json::decode($response->getBody());
     } else {
         return false;
     }
 }
 /**
  * @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);
 }
Exemplo n.º 27
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/>';
	
	}
Exemplo n.º 28
0
 /**
  * Makes a REST API request
  *
  * @param $url - URL
  * @param string $method - HTTP Method
  * @param array $data - raw POST data
  * @return Zend_Http_Response
  */
 public function makeRequest($url, $method = 'GET', $data = '')
 {
     try {
         $client = new Zend_Http_Client($url);
         $headers = array('Accept: application/json', 'Content-type: application/json');
         if (!empty($this->eapmBean->oauth_token)) {
             $headers[] = 'Authorization: OAuth oauth_token=' . $this->eapmBean->oauth_token;
         }
         $client->setHeaders($headers);
         if (!empty($data)) {
             $client->setRawData($data);
         }
         return $client->request($method);
     } catch (Exception $e) {
         $GLOBALS['log']->error($e->getMessage());
         return null;
     }
 }
Exemplo n.º 29
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']);
         }
     }
 }
Exemplo n.º 30
0
 public function send($url, $data)
 {
     if (empty($url)) {
         throw new Exception('$url not provided in Daiquiri_Model_Helper_Webhook::send()');
     }
     if (empty($data)) {
         throw new Exception('$data not provided in Daiquiri_Model_Helper_Webhook::send()');
     }
     $json = Zend_Json::encode($data);
     $client = new Zend_Http_Client($url);
     $client->setAdapter(new Zend_Http_Client_Adapter_Curl());
     $client->setMethod(Zend_Http_Client::POST);
     $client->setRawData($json, 'application/json');
     try {
         $response = $client->request();
     } catch (Zend_Http_Client_Exception $e) {
         // fail silently
     }
 }