/**
  * @return array
  */
 public function getResults($offset, $itemCountPerPage)
 {
     $query = $this->createSearchQuery($offset, $itemCountPerPage);
     $adapter = new Http\Client\Adapter\Curl();
     $adapter->setOptions(array('curloptions' => array(CURLOPT_SSL_VERIFYPEER => false)));
     $client = new Http\Client();
     $client->setAdapter($adapter);
     $client->setMethod('GET');
     $client->setUri($this->getOptions()->getSearchEndpoint() . $query);
     $response = $client->send();
     if (!$response->isSuccess()) {
         throw new Exception\RuntimeException("Invalid response received from CloudSearch.\n" . $response->getContent());
     }
     $results = Json::decode($response->getContent(), Json::TYPE_ARRAY);
     $this->count = $results['hits']['found'];
     if (0 == $this->count) {
         return array();
     }
     if ($this->getOptions()->getReturnIdResults()) {
         $results = $this->extractResultsToIdArray($results);
     }
     foreach ($this->getConverters() as $converter) {
         $results = $converter->convert($results);
     }
     return $results;
 }
Example #2
0
 function setPostRut($ruts)
 {
     foreach ($ruts as $rut) {
         $busqueda[] = explode('-', $rut[0]);
     }
     echo '<pre>';
     print_r($busqueda);
     echo '</pre>';
     $client = new Client('http://reca.poderjudicial.cl/', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true));
     $headers = $client->getRequest()->getHeaders();
     $cookies = new Zend\Http\Cookies($headers);
     $client->setMethod('GET');
     $response = $client->send();
     $client->setUri('http://reca.poderjudicial.cl/RECAWEB/AtPublicoViewAccion.do?tipoMenuATP=1');
     $cookies->addCookiesFromResponse($response, $client->getUri());
     $response = $client->send();
     $client->setUri("http://reca.poderjudicial.cl/RECAWEB/AtPublicoDAction.do");
     foreach ($busqueda as $rut) {
         $parametros = array('actionViewBusqueda' => '2', 'FLG_Busqueda' => '2', 'FLG_User_Valid' => '0', 'TIP_Lengueta' => 'tdDos', 'COD_Competencia' => 'C', 'tribunal_aux' => '-1', 'username_aux' => '', 'password_aux' => '', 'aux_codlibro' => '', 'aux_rolinterno' => '', 'aux_eracausa' => '', 'aux_codcorte' => '', 'RUT_Cod_Competencia' => 'C', 'RUT_Rut' => $rut[0], 'RUT_Rut_Db' => $rut[1], 'RIT_Cod_Competencia' => '0', 'RIT_Tip_Causa' => '0', 'RIT_Rol_Interno' => '', 'RIT_Era_Causa' => '', 'corte_Cod_Tribunal' => '-1', 'corte_Cod_Libro' => '0', 'corte_Rol_Interno' => '', 'corte_Era_Causa' => '', 'OPC_Cod_Corte' => '-1', 'OPC_Cod_Tribunal' => '-1', 'username' => '', 'password' => '');
         $client->setParameterPost($parametros);
         echo '<pre>';
         print_r($parametros);
         echo '</pre>';
         $response = $client->setMethod('POST')->send();
         $data = $response->getContent();
         echo '<pre>';
         print_r($response->getContent());
         echo '</pre>';
         die;
         $rut = $rut[0] . '-' . $rut[1];
         $dom = new Query($data);
         $resultados = $dom->execute('#divRecursos tr');
         $rols = $this->busquedaRut($resultados, $rut);
     }
 }
Example #3
0
 public function indexAction()
 {
     $client = new HttpClient();
     $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
     $method = $this->params()->fromQuery('method', 'get');
     $client->setUri('http://api-rest/san-restful');
     switch ($method) {
         case 'get':
             $id = $this->params()->fromQuery('id');
             $client->setMethod('GET');
             $client->setParameterGET(array('id' => $id));
             break;
         case 'get-list':
             $client->setMethod('GET');
             break;
         case 'create':
             $client->setMethod('POST');
             $client->setParameterPOST(array('name' => 'samsonasik'));
             break;
         case 'update':
             $data = array('name' => 'ikhsan');
             $adapter = $client->getAdapter();
             $adapter->connect('localhost', 80);
             $uri = $client->getUri() . '?id=1';
             // send with PUT Method, with $data parameter
             $adapter->write('PUT', new \Zend\Uri\Uri($uri), 1.1, array(), http_build_query($data));
             $responsecurl = $adapter->read();
             list($headers, $content) = explode("\r\n\r\n", $responsecurl, 2);
             $response = $this->getResponse();
             $response->getHeaders()->addHeaderLine('content-type', 'text/html; charset=utf-8');
             $response->setContent($content);
             return $response;
         case 'delete':
             $adapter = $client->getAdapter();
             $adapter->connect('localhost', 80);
             $uri = $client->getUri() . '?id=1';
             //send parameter id = 1
             // send with DELETE Method
             $adapter->write('DELETE', new \Zend\Uri\Uri($uri), 1.1, array());
             $responsecurl = $adapter->read();
             list($headers, $content) = explode("\r\n\r\n", $responsecurl, 2);
             $response = $this->getResponse();
             $response->getHeaders()->addHeaderLine('content-type', 'text/html; charset=utf-8');
             $response->setContent($content);
             return $response;
     }
     //if get/get-list/create
     $response = $client->send();
     if (!$response->isSuccess()) {
         // report failure
         $message = $response->getStatusCode() . ': ' . $response->getReasonPhrase();
         $response = $this->getResponse();
         $response->setContent($message);
         return $response;
     }
     $body = $response->getBody();
     $response = $this->getResponse();
     $response->setContent($body);
     return $response;
 }
 /**
  * Get Http client
  *
  * @param string $url         URL
  * @param bool   $resetParams Reset params
  * @param string $method      Method
  * @param string $adapterName Adapter name
  *
  * @return Client
  */
 protected function _getHttpClient($url, $resetParams = false, $method = Request::METHOD_GET, $adapterName = self::CONNECTION_CURL_ADAPTER)
 {
     $this->_httpClient = new Client($url);
     $this->_httpClient->resetParameters($resetParams);
     $this->_httpClient->setMethod($method)->setAdapter($adapterName);
     return $this->_httpClient;
 }
 /**
  * {@inheritDoc}
  */
 public function get($uri, array $headers = [])
 {
     $this->client->resetParameters();
     $this->client->setMethod('GET');
     $this->client->setHeaders(new Headers());
     $this->client->setUri($uri);
     if (!empty($headers)) {
         $this->injectHeaders($headers);
     }
     $response = $this->client->send();
     return new Response($response->getStatusCode(), $response->getBody(), $this->prepareResponseHeaders($response->getHeaders()));
 }
 /**
  * {@inheritdoc}
  */
 public function send($url, $payload)
 {
     try {
         $response = $this->client->setMethod('POST')->setUri($url)->setRawBody($payload)->setHeaders($this->getHeaders(true))->send();
     } catch (RuntimeException $e) {
         throw TcpException::transportError($e);
     }
     if ($response->getStatusCode() !== 200) {
         throw HttpException::httpError($response->getReasonPhrase(), $response->getStatusCode());
     }
     return $response->getBody();
 }
Example #7
0
 /**
  * Constructor
  *
  * @param string            $base     Base URL for Pazpar2
  * @param \Zend\Http\Client $client   An HTTP client object
  * @param bool              $autoInit Should we auto-initialize the Pazpar2
  * connection?
  */
 public function __construct($base, \Zend\Http\Client $client, $autoInit = false)
 {
     $this->base = $base;
     if (empty($this->base)) {
         throw new \Exception('Missing Pazpar2 base URL.');
     }
     $this->client = $client;
     $this->client->setMethod(Request::METHOD_GET);
     // always use GET
     if ($autoInit) {
         $this->init();
     }
 }
 /**
  * Redirects the user to a YUML graph drawn with the provided `dsl_text`
  *
  * @return \Zend\Http\Response
  *
  * @throws \UnexpectedValueException if the YUML service answered incorrectly
  */
 public function indexAction()
 {
     /* @var $request \Zend\Http\Request */
     $request = $this->getRequest();
     $this->httpClient->setMethod(Request::METHOD_POST);
     $this->httpClient->setParameterPost(array('dsl_text' => $request->getPost('dsl_text')));
     $response = $this->httpClient->send();
     if (!$response->isSuccess()) {
         throw new \UnexpectedValueException('HTTP Request failed');
     }
     /* @var $redirect \Zend\Mvc\Controller\Plugin\Redirect */
     $redirect = $this->plugin('redirect');
     return $redirect->toUrl('http://yuml.me/' . $response->getBody());
 }
Example #9
0
 /**
  * Add a new subscription
  *
  * @return JsonModel
  */
 public function create($data)
 {
     $username = $this->params()->fromRoute('username');
     $usersTable = $this->getTable('UsersTable');
     $user = $usersTable->getByUsername($username);
     $userFeedsTable = $this->getTable('UserFeedsTable');
     $rssLinkXpath = '//link[@type="application/rss+xml"]';
     $faviconXpath = '//link[@rel="shortcut icon"]';
     $client = new Client($data['url']);
     $client->setEncType(Client::ENC_URLENCODED);
     $client->setMethod(\Zend\Http\Request::METHOD_GET);
     $response = $client->send();
     if ($response->isSuccess()) {
         $html = $response->getBody();
         $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
         $dom = new Query($html);
         $rssUrl = $dom->execute($rssLinkXpath);
         if (!count($rssUrl)) {
             throw new Exception('Rss url not found in the url provided', 404);
         }
         $rssUrl = $rssUrl->current()->getAttribute('href');
         $faviconUrl = $dom->execute($faviconXpath);
         if (count($faviconUrl)) {
             $faviconUrl = $faviconUrl->current()->getAttribute('href');
         } else {
             $faviconUrl = null;
         }
     } else {
         throw new Exception("Website not found", 404);
     }
     $rss = Reader::import($rssUrl);
     return new JsonModel(array('result' => $userFeedsTable->create($user->id, $rssUrl, $rss->getTitle(), $faviconUrl)));
 }
Example #10
0
 /**
  * @return Workspace
  */
 public function fetch()
 {
     $events = $this->getEventManager();
     $event = new DeployEvent(null, $this);
     $events->trigger(DeployEvent::EVENT_FETCH_PRE, $event);
     // Check for filename, if any
     $response = $this->client->setMethod(Request::METHOD_HEAD)->send();
     $destination = $this->getStreamPath($response->getHeaders());
     // retrieve file
     $this->client->setMethod(Request::METHOD_GET)->setStream($destination->getPathname())->send();
     // create build file
     $workspace = new Workspace($destination->getPathname());
     $event->setWorkspace($workspace);
     $events->trigger(DeployEvent::EVENT_FETCH_POST, $event);
     return $workspace;
 }
Example #11
0
 function PlanJSONManager($action, $url, $requestjson, $uid)
 {
     $request = new Request();
     $request->getHeaders()->addHeaders(array('Content-Type' => 'application/json; charset=UTF-8'));
     //$url="";
     try {
         $request->setUri($url);
         $request->setMethod($action);
         $client = new Client();
         if ($action == 'PUT' || $action == 'POST') {
             $client->setUri($url);
             $client->setMethod($action);
             $client->setRawBody($requestjson);
             $client->setEncType('application/json');
             $response = $client->send();
             return $response;
         } else {
             $response = $client->dispatch($request);
             //var_dump(json_decode($response->getBody(),true));
             return $response;
         }
     } catch (\Exception $e) {
         $e->getTrace();
     }
     return null;
 }
 public static function getLatLng($address)
 {
     $latLng = [];
     try {
         $url = sprintf('http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false', $address);
         $client = new Client($url);
         $client->setAdapter(new Curl());
         $client->setMethod('GET');
         $client->setOptions(['curloptions' => [CURLOPT_HEADER => false]]);
         $response = $client->send();
         $body = $response->getBody();
         $result = Json\Json::decode($body, 1);
         $latLng = ['lat' => $result['results'][0]['geometry']['location']['lat'], 'lng' => $result['results'][0]['geometry']['location']['lng']];
         $isException = false;
     } catch (\Zend\Http\Exception\RuntimeException $e) {
         $isException = true;
     } catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $e) {
         $isException = true;
     } catch (Json\Exception\RuntimeException $e) {
         $isException = true;
     } catch (Json\Exception\RecursionException $e2) {
         $isException = true;
     } catch (Json\Exception\InvalidArgumentException $e3) {
         $isException = true;
     } catch (Json\Exception\BadMethodCallException $e4) {
         $isException = true;
     }
     if ($isException === true) {
         //código em caso de problemas no decode
     }
     return $latLng;
 }
 /**
  * @param MessageInterface|Message $message
  * @return mixed|void
  * @throws RuntimeException
  */
 public function send(MessageInterface $message)
 {
     $config = $this->getSenderOptions();
     $serviceURL = "http://letsads.com/api";
     $body = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><request></request>');
     $auth = $body->addChild('auth');
     $auth->addChild('login', $config->getUsername());
     $auth->addChild('password', $config->getPassword());
     $messageXML = $body->addChild('message');
     $messageXML->addChild('from', $config->getSender());
     $messageXML->addChild('text', $message->getMessage());
     $messageXML->addChild('recipient', $message->getRecipient());
     $client = new Client();
     $client->setMethod(Request::METHOD_POST);
     $client->setUri($serviceURL);
     $client->setRawBody($body->asXML());
     $client->setOptions(['sslverifypeer' => false, 'sslallowselfsigned' => true]);
     try {
         $response = $client->send();
     } catch (Client\Exception\RuntimeException $e) {
         throw new RuntimeException("Failed to send sms", null, $e);
     }
     try {
         $responseXML = new \SimpleXMLElement($response->getBody());
     } catch (\Exception $e) {
         throw new RuntimeException("Cannot parse response", null, $e);
     }
     if ($responseXML->name === 'error') {
         throw new RuntimeException("LetsAds return error (" . $responseXML->description . ')');
     }
 }
Example #14
0
 /**
  * Efetua consulta de cep.
  * 
  * @param type $cep
  * @return type
  * @throws Exception
  */
 public function addressFromCep($cep)
 {
     if (!file_exists(self::CONFIG_FILE)) {
         throw new Exception("Arquivo de configurações do cliente BYJG não existe");
     }
     $config = (include self::CONFIG_FILE);
     $result = array('found' => false);
     try {
         // Requisicao ao BYJG que prove base de dados gratuita para CEP
         $byJg = new Client(self::HOST);
         $byJg->setMethod(Request::METHOD_POST);
         $byJg->setParameterPost(array('httpmethod' => 'obterlogradouroauth', 'cep' => $cep, 'usuario' => $config['username'], 'senha' => $config['password']));
         $response = $byJg->send();
         if ($response->isOk()) {
             // captura resultado e organiza dados
             $body = preg_replace("/^OK\\|/", "", $response->getBody());
             // Separa as partes do CEP
             $parts = explode(", ", $body);
             if (count($parts) <= 1) {
                 throw new Exception("Resposta ByJG não pode suprir CEP como esperado");
             }
             $result['found'] = true;
             list($result['logradouro'], $result['bairro'], $result['cidade'], $result['estado'], $result['codIbge']) = $parts;
         }
     } catch (Exception $e) {
         Firephp::getInstance()->err($e->__toString());
     }
     return $result;
 }
Example #15
0
 /**
  * Get a read-stream for a file
  *
  * @param $path
  * @return array|bool
  */
 public function readStream($path)
 {
     $headers = ['User-Agent' => 'testing/1.0', 'Accept' => 'application/json', 'X-Foo' => ['Bar', 'Baz'], 'custom' => 'cust'];
     $stream = \GuzzleHttp\Stream\Stream::factory('contents...');
     $client = new \GuzzleHttp\Client(['headers' => $headers]);
     $resource = fopen('a.gif', 'r');
     $request = $client->put($this->api_url . 'upload', ['body' => $resource]);
     prn($client, $request);
     echo $request->getBody();
     exit;
     $location = $this->applyPathPrefix($path);
     $this->client->setMethod('PUT');
     $this->client->setUri($this->api_url . 'upload');
     $this->client->setParameterPost(array_merge($this->auth_param, ['location' => $location]));
     //        $this->client
     //            //->setHeaders(['path: /usr/local....'])
     //            ->setFileUpload('todo.txt','r')
     //            ->setRawData(fopen('todo.txt','r'));
     $fp = fopen('todo.txt', "r");
     $curl = $this->client->getAdapter();
     $curl->setCurlOption(CURLOPT_PUT, 1)->setCurlOption(CURLOPT_RETURNTRANSFER, 1)->setCurlOption(CURLOPT_INFILE, $fp)->setCurlOption(CURLOPT_INFILESIZE, filesize('todo.txt'));
     //  prn($curl->setOutputStream($fp));
     $response = $this->client->send();
     prn($response->getContent(), json_decode($response->getContent()));
     exit;
 }
Example #16
0
File: OVH.php Project: pontifex/sms
 /**
  * @param Struct\SMS $item
  * @return Client
  */
 protected function makeClient(Struct\SMS $item)
 {
     $client = new Client();
     $client->setUri($this->prepareUrl($item));
     $client->setMethod('GET');
     return $client;
 }
Example #17
0
 /**
  * Call MetaLib X-server
  *
  * @param string $operation X-Server operation
  * @param array  $params    URL Parameters
  *
  * @return mixed simpleXMLElement
  * @throws \Exception
  */
 protected function call($operation, $params)
 {
     $this->debug("Call: {$this->host}: {$operation}: " . var_export($params, true));
     // Declare UTF-8 encoding so that SimpleXML won't encode characters.
     $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><x_server_request/>');
     $op = $xml->addChild($operation);
     $this->paramsToXml($op, $params);
     $this->client->resetParameters();
     $this->client->setUri($this->host);
     $this->client->setParameterPost(['xml' => $xml->asXML()]);
     $result = $this->client->setMethod('POST')->send();
     if (!$result->isSuccess()) {
         throw new \Exception($result->getBody());
     }
     $xml = $result->getBody();
     // Remove invalid XML fields (these were encountered in record Ppro853_304965
     // from FIN05707)
     $xml = preg_replace('/<controlfield tag="   ">.*?<\\/controlfield>/', '', $xml);
     if ($xml = simplexml_load_string($xml)) {
         $errors = $xml->xpath('//local_error | //global_error');
         if (!empty($errors)) {
             if ($errors[0]->error_code == 6026) {
                 throw new \Exception('Search timed out');
             }
             throw new \Exception($errors[0]->asXML());
         }
         $result = $xml;
     }
     return $result;
 }
Example #18
0
 /**
  * Submit REST Request
  *
  * @param string $method  HTTP Method to use: GET or POST
  * @param array  $params  An array of parameters for the request
  * @param bool   $process Should we convert the MARCXML?
  *
  * @return string|SimpleXMLElement The response from the XServer
  */
 protected function call($method = 'GET', $params = null, $process = true)
 {
     if ($params) {
         $query = ['version=' . $this->sruVersion];
         foreach ($params as $function => $value) {
             if (is_array($value)) {
                 foreach ($value as $additional) {
                     $additional = urlencode($additional);
                     $query[] = "{$function}={$additional}";
                 }
             } else {
                 $value = urlencode($value);
                 $query[] = "{$function}={$value}";
             }
         }
         $queryString = implode('&', $query);
     }
     $this->debug('Connect: ' . print_r($this->host . '?' . $queryString, true));
     // Send Request
     $this->client->resetParameters();
     $this->client->setUri($this->host . '?' . $queryString);
     $result = $this->client->setMethod($method)->send();
     $this->checkForHttpError($result);
     // Return processed or unprocessed response, as appropriate:
     return $process ? $this->process($result->getBody()) : $result->getBody();
 }
 /**
  *
  * @param string $jotFormUrl        	
  * @throws UnableToRetrieveJotFormFile
  * @return $localFilePath
  */
 public function downloadFromJotForm($jotFormUrl, $password)
 {
     $client = new Client();
     $client->setUri($jotFormUrl);
     $client->setOptions(array('maxredirects' => 2, 'timeout' => 30));
     // Set Certification Path when https is used - does not work (yet)
     if (strpos($jotFormUrl, 'https:') === 0) {
         $client->setOptions(array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_SSL_VERIFYPEER => FALSE)));
     }
     // will use temp file
     $client->setStream();
     // Password, if set
     if (!empty($password)) {
         $client->setMethod(Request::METHOD_POST);
         $client->setParameterPost(array('passKey' => $password));
     }
     $response = $client->send();
     if ($response->getStatusCode() != 200) {
         throw new UnableToRetrieveJotFormFile('Wront StatusCode: ' . $response->getStatusCode() . ' (StatusCode=200 expected)');
     }
     // Copy StreamInput
     $tmpName = tempnam('/tmp', 'jotFormReport_');
     copy($response->getStreamName(), $tmpName);
     // Add to delete late
     $this->downloads[] = $tmpName;
     return $tmpName;
 }
Example #20
0
 /**
  * @return Model\File[]
  * @throws \Zend_Http_Client_Exception
  */
 private function _upload()
 {
     $this->_client->setUri(implode('/', [self::getConfig()['uri'], 'file/upload']));
     $this->_client->setMethod('POST');
     $filesInfo = json_decode($this->_client->send()->getBody(), true);
     return $this->_convertFilesInfoToObject($filesInfo);
 }
Example #21
0
 /**
  * Make an API call
  *
  * @param string $method GET or POST
  * @param array  $params Parameters to send
  *
  * @return \SimpleXMLElement
  */
 protected function call($method = 'GET', $params = null)
 {
     if ($params) {
         $query = [];
         foreach ($params as $function => $value) {
             if (is_array($value)) {
                 foreach ($value as $additional) {
                     $additional = urlencode($additional);
                     $query[] = "{$function}={$additional}";
                 }
             } else {
                 $value = urlencode($value);
                 $query[] = "{$function}={$value}";
             }
         }
         $queryString = implode('&', $query);
     }
     $dbs = explode(',', $this->dbs);
     $dblist = '';
     foreach ($dbs as $db) {
         $dblist .= "&db=" . $db;
     }
     $this->debug('Connect: ' . print_r($this->base . '?' . $queryString . $dblist, true));
     // Send Request
     $this->client->resetParameters();
     $this->client->setUri($this->base . '?' . $queryString . $dblist);
     $result = $this->client->setMethod($method)->send();
     $body = $result->getBody();
     $xml = simplexml_load_string($body);
     $this->debug(print_r($xml, true));
     return $body;
 }
 /**
  * @todo whats wrong with SSL?
  * @return array
  */
 public function doRequest()
 {
     $url = 'https://www.mvg.de/.rest/betriebsaenderungen/api/interruptions';
     $client = new Client($url, array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_SSL_VERIFYPEER => FALSE)));
     $client->setMethod(\Zend\Http\Request::METHOD_GET);
     return ZendJson::decode($client->send()->getBody());
 }
Example #23
0
 /**
  * Send a text message to the specified provider.
  *
  * @param string $provider The provider ID to send to
  * @param string $to       The phone number at the provider
  * @param string $from     The email address to use as sender
  * @param string $message  The message to send
  *
  * @throws \VuFind\Exception\Mail
  * @return void
  */
 public function text($provider, $to, $from, $message)
 {
     $url = $this->getApiUrl($to, $message);
     try {
         $result = $this->client->setMethod('GET')->setUri($url)->send();
     } catch (\Exception $e) {
         throw new MailException($e->getMessage());
     }
     $response = $result->isSuccess() ? trim($result->getBody()) : '';
     if (empty($response)) {
         throw new MailException('Problem sending text.');
     }
     if ('ID:' !== substr($response, 0, 3)) {
         throw new MailException($response);
     }
     return true;
 }
 public function indexAction()
 {
     $client = new HttpClient();
     $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
     $method = $this->params()->fromRoute('param', 'get-list');
     $client->setUri('http://localhost/album-rest');
     switch ($method) {
         case 'get':
             $id = $this->params()->fromRoute('id', 2);
             $client->setMethod('GET');
             $client->setParameterGET(array('id' => $id));
             break;
         case 'get-list':
             $client->setMethod('GET');
             break;
         case 'create':
             $client->setMethod('POST');
             $client->setParameterPOST(array('title' => 'Bob Marley LIVE', 'artist' => 'Bob Marley'));
             break;
         case 'update':
             $id = $this->params()->fromRoute('id', 2);
             $data = array('title' => 'Show 90 Anos Ao Vivo', 'artist' => 'Zeze di Camargo & Luciano');
             $client->setMethod('PUT');
             $client->setParameterPOST($data);
             $client->setParameterGET(array('id' => $id));
             break;
         case 'delete':
             $id = $this->params()->fromRoute('id', 2);
             $client->setMethod('DELETE');
             $client->setParameterGET(array('id' => $id));
             break;
     }
     //send request
     $response = $client->send();
     if (!$response->isSuccess()) {
         //error
         $message = $response->getStatusCode() . ': ' . $response->getReasonPhrase();
         $response = $this->getResponse();
         $response->setContent($message);
         return $response;
     }
     $body = $response->getBody();
     $response = $this->getResponse();
     $response->setContent($body);
     return $response;
 }
 /**
  * @param string $method
  * @param string $url
  * @param array [optional] $params
  */
 public function request($method, $url, $params = [])
 {
     $this->httpClient->setUri($this->moduleOptions->getApiUrl() . '/' . ltrim($url, '/'));
     $this->httpClient->setMethod($method);
     if (!is_null($params)) {
         if ($method == 'post' || $method == 'put') {
             $this->httpClient->setEncType(HttpClient::ENC_FORMDATA);
             $this->httpClient->setParameterPost($params);
         } else {
             $this->httpClient->setEncType(HttpClient::ENC_URLENCODED);
             $this->httpClient->setParameterGet($params);
         }
     }
     $response = $this->httpClient->send();
     $data = json_decode($response->getBody(), true);
     return $data;
 }
Example #26
0
 public function fetch($cnpj)
 {
     $client = new Client('http://www.sintegra.es.gov.br/resultado.php');
     $client->setMethod(Request::METHOD_POST);
     $client->setParameterPost(['num_cnpj' => $cnpj, 'botao' => 'Consultar', 'num_ie' => '']);
     $response = $client->send();
     return $response;
 }
 /**
  * Return an existing client or create a new one
  * @return HttpClient
  */
 public function getHttpClient()
 {
     if (!$this->httpClient) {
         $this->httpClient = new HttpClient(null, array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl'));
         $this->httpClient->setMethod('POST');
     }
     return $this->httpClient;
 }
Example #28
0
 protected function getClient($url, $query, $method = 'POST')
 {
     $client = new Client();
     $client->setUri($url);
     if ($method == 'POST') {
         $client->setMethod(Request::METHOD_POST);
         if ($query) {
             $client->setParameterPost($query);
         }
     } else {
         $client->setMethod(Request::METHOD_GET);
         if ($query) {
             $client->setParameterGet($query);
         }
     }
     return $client;
 }
 /**
  */
 public function hit($url, $method = "GET", $params)
 {
     $client = new Client($url);
     $client->setMethod($method);
     $client->setParameterPost($params);
     $return = $client->send();
     return $return->getContent();
 }
Example #30
0
 /**
  * @param Struct\SMS $item
  * @return Client
  */
 protected function makeClient(Struct\SMS $item)
 {
     $client = new Client();
     $client->setOptions(array('sslverifypeer' => false));
     $client->setUri($this->prepareUrl($item));
     $client->setMethod('GET');
     return $client;
 }