コード例 #1
1
 /**
  * @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;
 }
コード例 #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);
     }
 }
コード例 #3
0
ファイル: Client.php プロジェクト: php-http/zend-adapter
 /**
  * {@inheritdoc}
  */
 public function sendRequest(RequestInterface $request)
 {
     $request = $this->sanitizeRequest($request);
     $headers = new Headers();
     foreach ($request->getHeaders() as $key => $value) {
         $headers->addHeader(new GenericHeader($key, $request->getHeaderLine($key)));
     }
     $zendRequest = new Request();
     $zendRequest->setMethod($request->getMethod());
     $zendRequest->setUri((string) $request->getUri());
     $zendRequest->setHeaders($headers);
     $zendRequest->setContent($request->getBody()->getContents());
     $options = ['httpversion' => $request->getProtocolVersion()];
     if (extension_loaded('curl')) {
         $options['curloptions'] = [CURLOPT_HTTP_VERSION => $this->getProtocolVersion($request->getProtocolVersion())];
     }
     $this->client->setOptions($options);
     if ($this->client->getAdapter() instanceof ZendClient\Adapter\Curl && $request->getMethod()) {
         $request = $request->withHeader('Content-Length', '0');
     }
     try {
         $zendResponse = $this->client->send($zendRequest);
     } catch (RuntimeException $exception) {
         throw new NetworkException($exception->getMessage(), $request, $exception);
     }
     return $this->responseFactory->createResponse($zendResponse->getStatusCode(), $zendResponse->getReasonPhrase(), $zendResponse->getHeaders()->toArray(), $zendResponse->getContent(), $zendResponse->getVersion());
 }
コード例 #4
0
 /**
  * @param Request $request
  * @return Response
  */
 protected function proceed(Http $httpUri, Request $request)
 {
     $httpUri = $httpUri->parse($this->moduleOptions->getApiUrl() . $httpUri->toString());
     $request->setUri($httpUri);
     $this->httpClient->setAuth($this->moduleOptions->getUserName(), $this->moduleOptions->getPassword());
     $this->httpClient->setOptions(array('sslverifypeer' => false));
     return $this->httpClient->send($request);
 }
コード例 #5
0
ファイル: Zend2HttpAdapter.php プロジェクト: lamenath/fbp
 /**
  * {@inheritdoc}
  */
 protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
 {
     $this->client->resetParameters(true)->setOptions(array('httpversion' => $internalRequest->getProtocolVersion(), 'timeout' => $this->getConfiguration()->getTimeout(), 'maxredirects' => 0))->setUri($url = (string) $internalRequest->getUrl())->setMethod($internalRequest->getMethod())->setHeaders($this->prepareHeaders($internalRequest))->setRawBody($this->prepareBody($internalRequest));
     try {
         $response = $this->client->send();
     } catch (\Exception $e) {
         throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage());
     }
     return $this->getConfiguration()->getMessageFactory()->createResponse($response->getStatusCode(), $response->getReasonPhrase(), $response->getVersion(), $response->getHeaders()->toArray(), BodyNormalizer::normalize(function () use($response) {
         return $response instanceof Stream ? $response->getStream() : $response->getBody();
     }, $internalRequest->getMethod()));
 }
コード例 #6
0
ファイル: ServiceYQL.php プロジェクト: machek/mmyql
 /**
  * @param $select
  * @param $from
  * @param $where
  * @param $format
  */
 public function executeQuery($select, $from, $where, $format = 'json')
 {
     $yql_query = "select {$select} from {$from} where {$where} ";
     $this->client->setParameterGet(array('q' => $yql_query, 'format' => $format));
     $response = $this->client->send();
     /* @var $response \Zend\Http\Response */
     if ($response->isSuccess()) {
         return $response->getBody();
     } else {
         throw new \Exception('Error - Response code: ' . $response->getStatusCode() . ' - query - ' . $yql_query);
     }
 }
コード例 #7
0
 /**
  * {@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()));
 }
コード例 #8
0
 /**
  * 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());
 }
コード例 #9
0
 /**
  * @param  Request  $request
  * @return Response
  */
 public function request(Request $request)
 {
     $headers = new Headers();
     $headers->addHeaders($request->getHeaders());
     $zendRequest = new ZendRequest();
     $zendRequest->setVersion($request->getProtocolVersion());
     $zendRequest->setMethod($request->getMethod());
     $zendRequest->setUri((string) $request->getUrl());
     $zendRequest->setHeaders($headers);
     $zendRequest->setContent($request->getContent());
     /** @var ZendResponse $zendResponse */
     $zendResponse = $this->client->send($zendRequest);
     return new Response((string) $zendResponse->getVersion(), $zendResponse->getStatusCode(), $zendResponse->getReasonPhrase(), $zendResponse->getHeaders()->toArray(), $zendResponse->getContent());
 }
コード例 #10
0
 /**
  * Make a remote call to freegeoip.net to detect country of current customer session and store it into session
  *
  * @return $this
  */
 public function saveVisitorData($observer)
 {
     $clientIP = $this->_request->getClientIp();
     $httpClient = new Client();
     $clientIP = $this->getRandomeIp($clientIP);
     $uri = self::URL_GEO_IP_SITE . $clientIP;
     $httpClient->setUri($uri);
     $httpClient->setOptions(array('timeout' => 30));
     try {
         $response = JsonDecoder::decode($httpClient->send()->getBody());
         $this->_customerSession->setVisitorData($response);
         //save to database
         $currenttime = date('Y-m-d H:i:s');
         $model = $this->_objectManager->create('Bluecom\\Freegeoip\\Model\\Visitor');
         $model->setData('visitor_ip', $response->ip);
         $model->setData('country_code', $response->country_code);
         $model->setData('country_name', $response->country_name);
         $model->setData('region_code', $response->region_code);
         $model->setData('region_name', $response->region_name);
         $model->setData('city', $response->city);
         $model->setData('zip_code', $response->zip_code);
         $model->setData('latitude', $response->latitude);
         $model->setData('longitude', $response->longitude);
         $model->setData('metro_code', $response->metro_code);
         $model->setData('browser', $_SERVER['HTTP_USER_AGENT']);
         $model->setData('os', php_uname());
         $model->setData('created', $currenttime);
         $model->save();
     } catch (\Exception $e) {
         $this->_logger->critical($e);
     }
     return $this;
 }
コード例 #11
0
ファイル: Storage.php プロジェクト: execrot/storage-client
 /**
  * @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);
 }
コード例 #12
0
 /**
  * @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());
 }
コード例 #13
0
ファイル: Gist.php プロジェクト: ocramius/ocramius
 public function persist(HelpReport $report)
 {
     $data = ['description' => 'Report generated via Ocramius CLI', 'files' => ['report.json' => ['content' => json_encode($report)]], 'public' => false];
     $request = new Request();
     $request->setUri('https://api.github.com/gists');
     $request->setContent(json_encode($data));
     $request->setMethod(Request::METHOD_POST);
     $request->getHeaders()->addHeader(ContentType::fromString('Content-Type: application/json'));
     $request->getHeaders()->addHeaderLine('X-Requested-With: Ocramius CLI');
     $response = $this->client->send($request);
     if (!$response->isSuccess()) {
         throw new \UnexpectedValueException('Could not obtain a valid GIST from the github API');
     }
     $response = json_decode($response->getBody(), true);
     return $response['html_url'];
 }
コード例 #14
0
ファイル: GeoService.php プロジェクト: omusico/casawp
 public function findRegion($country, $query)
 {
     $request = new Request();
     $request->setMethod(Request::METHOD_GET);
     foreach ($query as $key => $value) {
         $request->getQuery()->set($key, $value);
     }
     $request->getHeaders()->addHeaderLine('Accept', 'application/json');
     switch ($country) {
         case 'CH':
             $request->setUri($this->config['url'] . '/ch-region');
             break;
         default:
             $request->setUri($this->config['url'] . '/ch-region');
             break;
     }
     $client = new Client();
     $response = $client->send($request);
     $body = $response->getBody();
     $result = json_decode($body, true);
     if ($result) {
         return $result['_embedded']['ch_region'];
     }
     /*echo "<textarea cols='100' rows='30' style='position:relative; z-index:10000; width:inherit; height:200px;'>";
       print_r($body);
       echo "</textarea>";
       die();*/
     return null;
 }
コード例 #15
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;
 }
コード例 #16
0
ファイル: IpInfo.php プロジェクト: arbi/MyCode
 /**
  * @param $ipString
  * @return IdentityInformation
  * @throws \Zend\Validator\Exception\InvalidArgumentException
  */
 public function getIpInfo($ipString)
 {
     $ipValidator = new Ip();
     if (!$ipValidator->isValid($ipString)) {
         throw new InvalidArgumentException();
     }
     // creating request object
     $request = new Request();
     $request->setUri($this->endPoint . $ipString . '/json');
     $client = new Client();
     $adapter = new Client\Adapter\Curl();
     $adapter->setCurlOption(CURLOPT_TIMEOUT_MS, 500);
     $client->setAdapter($adapter);
     $response = $client->send($request);
     $data = $response->getBody();
     $dataArray = json_decode($data);
     $identityInformation = new IdentityInformation();
     $identityInformation->setCountry(isset($dataArray->country) ? $dataArray->country : '');
     $identityInformation->setRegion(isset($dataArray->region) ? $dataArray->region : '');
     $identityInformation->setCity(isset($dataArray->city) ? $dataArray->city : '');
     $identityInformation->setLocation(isset($dataArray->loc) ? $dataArray->loc : '');
     $identityInformation->setProvider(isset($dataArray->org) ? $dataArray->org : '');
     $identityInformation->setHostName(isset($dataArray->hostname) ? $dataArray->hostname : '');
     return $identityInformation;
 }
コード例 #17
0
 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;
 }
コード例 #18
0
ファイル: AbstractHostApi.php プロジェクト: mslib/remote-host
 /**
  * Executes a remote api action by action name
  *
  * @param string $actionName         the action name to execute
  * @param array  $requestParameters  the request parameters (keys/values) to use in the action execution
  * @param string $content            the content to be set in the body of the request
  * @param array  $urlBuildParameters the url build adds on parameter array
  * @param array  $headersValue       the header value array to override default header values
  *
  * @return null|\Msl\RemoteHost\Response\Wrapper\ResponseWrapperInterface
  *
  * @throws \Msl\RemoteHost\Exception\NotConfiguredActionException
  * @throws \Msl\RemoteHost\Exception\BadConfiguredActionException
  * @throws \Msl\RemoteHost\Exception\UnsuccessApiActionException
  */
 public function execute($actionName, array $requestParameters = array(), $content = "", array $urlBuildParameters = array(), array $headersValue = array())
 {
     // Getting configured action request object
     $actionRequest = $this->getActionRequestByName($actionName);
     if (!$actionRequest instanceof AbstractActionRequest) {
         throw new BadConfiguredActionException($this->getNotValidRequestExMsg($actionRequest), $actionRequest);
     }
     // Setting all request parameters with the given values (request parameters array)
     try {
         // Merging request headers with common dynamic headers
         $headersValue = array_merge($this->commonDynamicHeaders, $headersValue);
         $actionRequest->configure($requestParameters, $content, $urlBuildParameters, $headersValue);
     } catch (\Exception $ex) {
         throw new NotConfiguredActionException(sprintf('[%s] An error occured while configuring the action \'%s\': \'%s\'.', $this->getApiName(), $actionName, $ex->getMessage()), $actionRequest);
     }
     // We configure the Zend\Http\Client object and we send the request
     $actionRequest->setClientEncType($this->client);
     // Getting the response
     $response = null;
     try {
         $response = $this->client->send($actionRequest);
     } catch (ZendExceptionInterface $ze) {
         throw new UnsuccessApiActionException(sprintf('[%s] An exception was caught while running the action \'%s\'. Error code \'%s\', message \'%s\'.', $this->getApiName(), $actionName, $ze->getCode(), $ze->getMessage()), $actionRequest, $response);
     }
     // Getting a proper ActionResponseInterface object instance
     $responseObj = $this->getResponseInstance($actionRequest->getResponseType(), $actionRequest->getResponseWrapper());
     // We check if there is a response object defined. If yes, we wrap its main content into a response wrapper object;
     if ($responseObj instanceof ActionResponseInterface) {
         $responseObj->setResponse($response);
         $responseObj->setRequestName($actionName);
         return $responseObj->getParsedResponse();
     }
     // if not, we return a null value.
     return null;
 }
コード例 #19
0
ファイル: Version.php プロジェクト: hmschreiner/GotCms
 /**
  * Fetches the version of the latest stable release.
  *
  * @return string
  */
 public static function getLatest()
 {
     if (null === self::$latestVersion) {
         self::$latestVersion = 'not available';
         $url = 'https://api.github.com/repos/GotCms/GotCms/git/refs/tags';
         try {
             $client = new Client($url, array('adatper' => 'Zend\\Http\\Client\\Adapter\\Curl', 'timeout' => 2, 'ssltransport' => STREAM_CRYPTO_METHOD_TLS_CLIENT, 'sslverifypeer' => false));
             $response = $client->send();
             if ($response->isSuccess()) {
                 $content = $response->getBody();
             }
         } catch (\Exception $e) {
             //Don't care
         }
         //Try to retrieve with file_get_contents
         if (empty($content)) {
             $content = @file_get_contents($url);
         }
         if (!empty($content)) {
             $apiResponse = Json::decode($content, Json::TYPE_ARRAY);
             // Simplify the API response into a simple array of version numbers
             $tags = array_map(function ($tag) {
                 return substr($tag['ref'], 10);
                 // Reliable because we're filtering on 'refs/tags/'
             }, $apiResponse);
             // Fetch the latest version number from the array
             self::$latestVersion = array_reduce($tags, function ($a, $b) {
                 return version_compare($a, $b, '>') ? $a : $b;
             });
         }
     }
     return self::$latestVersion;
 }
コード例 #20
0
 /**
  * @return CasResult
  */
 public function validate()
 {
     try {
         $uri = $this->createValidateUri();
     } catch (Adapter\Exception\InvalidArgumentException $e) {
         return new CasResult(CasResult::FAILURE, '', array($e->getMessage()));
     }
     $this->httpClient->resetParameters();
     $this->httpClient->setUri($uri);
     try {
         $response = $this->httpClient->send();
     } catch (Http\Exception\RuntimeException $e) {
         return new CasResult(CasResult::FAILURE_UNCATEGORIZED, '', array($e->getMessage()));
     }
     if (!$response->isSuccess()) {
         return new CasResult(CasResult::FAILURE_UNCATEGORIZED, '', array('HTTP response did not indicate success.'), $response->getBody());
     }
     $body = $response->getBody();
     $explodedResponse = explode("\n", $body);
     if (count($explodedResponse) < 2) {
         return new CasResult(CasResult::FAILURE_UNCATEGORIZED, '', array('Got an invalid CAS 1.0 response.'), $body);
     }
     $status = $explodedResponse[0];
     $identity = $explodedResponse[1];
     if ($status !== 'yes') {
         return new CasResult(CasResult::FAILURE_UNCATEGORIZED, '', array('Authentication failed.'), $body);
     }
     return new CasResult(CasResult::SUCCESS, $identity, array(), $body);
 }
コード例 #21
0
ファイル: Client.php プロジェクト: dsi-agpt/minibus
 protected function dispatchRequestAndDecodeResponse($url, $method, $data = null)
 {
     $request = new Request();
     $this->lastResponse = null;
     $request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept' => 'application/json', 'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0'));
     if (!empty($this->host)) {
         $request->getHeaders()->addHeaders(array('Host' => $this->host));
     }
     if (!empty($this->key)) {
         $request->getHeaders()->addHeaders(array('Authorization' => 'Bearer ' . $this->key));
     }
     $request->setUri($url);
     $request->setMethod($method);
     if (is_null($data)) {
         $data = array();
     }
     if (isset($this->key)) {
         $data["auth"] = $this->key;
     }
     if ($method == "POST" || $method == "PUT") {
         $request->setPost(new Parameters($data));
         if (isset($this->key)) {
             $request->setQuery(new Parameters(array('auth' => $this->key)));
         }
     } else {
         $request->setQuery(new Parameters($data));
     }
     $this->lastResponse = $this->httpClient->send($request);
     if ($this->lastResponse->isSuccess()) {
         return json_decode($this->lastResponse->getBody(), true);
     } else {
         return array('error' => true, 'headers' => array("code" => $this->lastResponse->getStatusCode(), "reasons" => $this->lastResponse->getReasonPhrase()), 'body' => json_decode($this->lastResponse->getBody(), true));
     }
 }
コード例 #22
0
ファイル: RESTJSONManager.php プロジェクト: shivap87/cost
 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;
 }
コード例 #23
0
ファイル: ByjgClient.php プロジェクト: braghimsistemas/zf2lib
 /**
  * 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;
 }
コード例 #24
0
 public function pharAction()
 {
     $client = $this->serviceLocator->get('zendServerClient');
     $client = new Client();
     if (defined('PHAR')) {
         // the file from which the application was started is the phar file to replace
         $file = $_SERVER['SCRIPT_FILENAME'];
     } else {
         $file = dirname($_SERVER['SCRIPT_FILENAME']) . '/zs-client.phar';
     }
     $request = new Request();
     $request->setMethod(Request::METHOD_GET);
     $request->setHeaders(Headers::fromString('If-Modified-Since: ' . gmdate('D, d M Y H:i:s T', filemtime($file))));
     $request->setUri('https://github.com/zendtech/ZendServerSDK/raw/master/bin/zs-client.phar');
     //$client->getAdapter()->setOptions(array('sslcapath' => __DIR__.'/../../../certs/'));
     $client->setAdapter(new Curl());
     $response = $client->send($request);
     if ($response->getStatusCode() == 304) {
         return 'Already up-to-date.';
     } else {
         ErrorHandler::start();
         rename($file, $file . '.' . date('YmdHi') . '.backup');
         $handler = fopen($file, 'w');
         fwrite($handler, $response->getBody());
         fclose($handler);
         ErrorHandler::stop(true);
         return 'The phar file was updated successfully.';
     }
 }
コード例 #25
0
ファイル: KingHost.php プロジェクト: ualisonaguiar/shome2
 public function pesquisaCep($strCEP)
 {
     $httpClient = new Client();
     $httpClient->setUri('http://webservice.kinghost.net/web_cep.php')->setParameterGet(array('auth' => $this->auth, 'formato' => 'json', 'cep' => $strCEP));
     $response = (object) json_decode($httpClient->send()->getBody(), true);
     return array('uf' => $response->uf, 'cidade' => $response->cidade, 'bairro' => $response->bairro, 'logradouro' => $response->logradouro, 'status' => $response->resultado ? true : false, 'message' => !$response->resultado ? 'CEP não encontrado' : '');
 }
コード例 #26
0
 public static function sendRequest($request)
 {
     $client = new Client();
     $response = $client->send($request);
     //envoie la requête au service REST
     return $response;
 }
コード例 #27
0
ファイル: HttpEngine.php プロジェクト: navtis/xerxes
 public function scrape($url)
 {
     $client = new Client($url);
     $records = 0;
     $response = $client->send();
     if ($response->isClientError()) {
         return $records;
     }
     $html = $response->getBody();
     //$html = $response->getBody();
     // although AIM25 is xhtml, it isn't quite valid enough
     // just to load into a domdocument
     //$dd = new \DOMDocument();
     //if (! $dd->loadHTML($html) )
     //{
     //    return $res;
     //}
     //$xp = new \DOMXPath($dd);
     //$el = $xp->query("//*[@id='content']/h1")->item(0);
     // so just brute-force it with a regex. Probably much quicker anyway
     if (preg_match('/ \\((\\d+) matches\\)/', $html, $matches) != 1) {
         return 0;
     }
     return $matches[1];
 }
コード例 #28
0
 /**
  * @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 . ')');
     }
 }
コード例 #29
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;
 }
コード例 #30
0
 /**
  *
  * @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;
 }