public function __invoke($par) { $config = $this->getController()->getServiceLocator()->get('config'); $lang = $this->getController()->getEvent()->getRouteMatch()->getParam('lang', 'en'); if (empty($config['geocoder_photon_url'])) { throw new \InvalidArgumentException('Now Service-Adress for Geo-Service available'); } $client = new \Zend\Http\Client($config['geocoder_photon_url']); $client->setMethod('GET'); $osmTags = ['tourism', 'aeroway', 'railway', 'amenity', 'historic', 'tunnel', 'mountain_pass', 'leisure', 'natural', 'bridge', 'waterway']; $osmTags = array_map(function ($i) { return urlencode('!' . $i); }, $osmTags); $uri = sprintf('%s?q=%s&lang=%s&osm_tag=%s', $config['geocoder_photon_url'], urlencode($par), $lang, implode('&osm_tag=', $osmTags)); $client->setUri($uri); $response = $client->send(); $result = $response->getBody(); $result = json_decode($result); $result = $result->features; foreach ($result as $key => $val) { $row = ['name' => property_exists($val->properties, 'name') ? $val->properties->name : '', 'postcode' => property_exists($val->properties, 'postcode') ? $val->properties->postcode : '', 'city' => property_exists($val->properties, 'city') ? $val->properties->city : '', 'street' => property_exists($val->properties, 'street') ? $val->properties->street : '', 'state' => property_exists($val->properties, 'state') ? $val->properties->state : '', 'country' => property_exists($val->properties, 'country') ? $val->properties->country : '', 'coordinates' => implode(":", $val->geometry->coordinates), 'osm_key' => property_exists($val->properties, 'osm_key') ? $val->properties->osm_key : '', 'osm_value' => property_exists($val->properties, 'osm_value') ? $val->properties->osm_value : '', 'osm_id' => property_exists($val->properties, 'osm_id') ? $val->properties->osm_id : '', 'data' => json_encode($val)]; $r[] = $row; } return $r; }
/** * Get Country User * * @param EventObserver $observer */ public function execute(EventObserver $observer) { if (!$this->_customerSession->getLocated()) { //$clientIP = $this->_request->getClientIp(); /* * Set static Ip to test * * DE : 194.55.30.46 * VN : 123.30.215.27 * PL : 212.77.98.9 * SG : 202.157.143.72 * **/ $clientIP = '123.30.215.27'; $uri = 'http://freegeoip.net/json/' . $clientIP; $httpClient = new \Zend\Http\Client(); $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = \Zend\Json\Decoder::decode($httpClient->send()->getBody()); $this->_customerSession->setLocationData($response); $this->_customerSession->setLocated(true); } catch (\Exception $e) { $this->_logger->critical($e); } } }
/** * Sends a request and returns a response * * @param CartRecover_Request $request * @return Cart_Recover_Response */ public function sendRequest(CartRecover_Request $request) { $this->client->setUri($request->getUri()); $this->client->setParameterGet($request->getParams()); $this->client->setMethod($request->getMethod()); $this->client->setHeaders(array('Accept' => 'application/json')); $this->response = $this->client->send(); if ($this->response->getHeaders()->get('Content-Type')->getFieldValue() != 'application/json') { throw new CartRecover_Exception_UnexpectedValueException("Unknown response format."); } $body = json_decode($this->response->getContent(), true); $response = new CartRecover_Response(); $response->setRawResponse($this->response->toString()); $response->setBody($body); $response->setHeaders($this->response->getHeaders()->toArray()); $response->setStatus($this->response->getReasonPhrase(), $this->response->getStatusCode()); return $response; }
function getJsonObject($channelId) { $client = new Zend\Http\Client(); $url = sprintf('http://api.thingspeak.com/channels/%d/feed.json', $channelId); $client->setUri($url)->setMethod(\Zend\Http\Request::METHOD_GET); $response = $client->send(); $responseObject = \Zend\Json\Json::decode($response->getBody()); if (-1 === $responseObject) { exit(sprintf('Nothing found under %s' . PHP_EOL, $url)); } return $responseObject; }
public function getCausas() { $cliente = new \Zend\Http\Client('http://civil.poderjudicial.cl', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true)); $headers = $cliente->getRequest()->getHeaders(); $cookies = new Zend\Http\Cookies($headers); $cliente->setMethod('GET'); $response = $cliente->send(); $cliente->setUri('http://civil.poderjudicial.cl/CIVILPORWEB/AtPublicoViewAccion.do?tipoMenuATP=1'); $cookies->addCookiesFromResponse($response, $cliente->getUri()); $response = $cliente->send(); echo '<pre>'; print_r($response); echo '</pre>'; }
/** * @param Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { $clientIP = "115.78.167.37"; // $clientIP = $this->_request->getClientIp(); $httpClient = new \Zend\Http\Client(); $uri = 'http://freegeoip.net/json/' . $clientIP; $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = \Zend\Json\Decoder::decode($httpClient->send()->getBody()); $this->_customerSession->setLocationData($response); $this->_customerSession->setLocated(true); } catch (\Exception $e) { $this->_logger->critical($e); } return $this; }
/** * Performs HTTP request to given $url using given HTTP $method. * Send additinal query specified by variable/value array, * On success returns HTTP response without headers, false on failure. * * @param string $url OpenID server url * @param string $method HTTP request method 'GET' or 'POST' * @param array $params additional qwery parameters to be passed with * @param int &$staus HTTP status code * request * @return mixed */ protected function _httpRequest($url, $method = 'GET', array $params = array(), &$status = null) { $client = $this->_httpClient; if ($client === null) { $client = new \Zend\Http\Client($url, array('maxredirects' => 4, 'timeout' => 15, 'useragent' => 'Zend_OpenId')); } else { $client->setUri($url); } $client->resetParameters(); if ($method == 'POST') { $client->setMethod(\Zend\Http\Client::POST); $client->setParameterPost($params); } else { $client->setMethod(\Zend\Http\Client::GET); $client->setParameterGet($params); } try { $response = $client->request(); } catch (\Exception $e) { $this->_setError('HTTP Request failed: ' . $e->getMessage()); return false; } $status = $response->getStatus(); $body = $response->getBody(); if ($status == 200 || $status == 400 && !empty($body)) { return $body; } else { $this->_setError('Bad HTTP response'); return false; } }
/** * Return a new HTTP client. * * @param string $url Target URL * @param string $method Request method * @param float $timeout Request timeout in seconds * * @return \Zend\Http\Client */ public function createClient($url = null, $method = \Zend\Http\Request::METHOD_GET, $timeout = null) { $client = new \Zend\Http\Client(); $client->setMethod($method); if (!empty($this->defaults)) { $client->setOptions($this->defaults); } if (null !== $this->defaultAdapter) { $client->setAdapter($this->defaultAdapter); } if (null !== $url) { $client->setUri($url); } if ($timeout) { $client->setOptions(array('timeout' => $timeout)); } $this->proxify($client); return $client; }
/** * Sends the data via cURL * @param array $params * @param integer $method * @param string $raw_body * @return Zend_Http_Response */ private function curl($orig_url, $params = array(), $method = Request::GET, $headers = array(), $remove_unsafe_params = true, $retry_count = 0) { try { if (is_null($orig_url) && defined('MO_API_URL')) { $orig_url = MO_API_URL; } else { if (is_null($orig_url)) { throw new \Exception('No url was provided and MO_API_URL is not defined'); } } $url = $orig_url . $this->getFunc(); if ($method == Request::DELETE || $method == Request::PUT) { if (isset($params['_id'])) { $url .= '/' . (isset($params['_id']) ? (int) $params['_id'] : 0); } } // remove any routing to prevent overwritting the url if ($remove_unsafe_params) { if (isset($params['module'])) { unset($params['module']); } if (isset($params['controller'])) { unset($params['controller']); } if (isset($params['action'])) { unset($params['action']); } if (isset($params['func'])) { unset($params['func']); } } // gots to do this so that transfer-encoding: chunked comes through properly $curl_adapter = new \Zend\Http\Client\Adapter\Curl(); // Enforce a 30 second timeout (default is unlimited) if ($this->getTimeout() > 0) { $curl_adapter->setCurlOption(CURLOPT_TIMEOUT, $this->getTimeout()); $curl_adapter->setCurlOption(CURLOPT_CONNECTTIMEOUT, $this->getTimeout()); } //$curl_adapter->setCurlOption(CURLOPT_ENCODING , "gzip"); $curl_adapter->setCurlOption(CURLOPT_SSL_VERIFYPEER, false); $curl_adapter->setCurlOption(CURLOPT_USERAGENT, 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'); $http_client = new \Zend\Http\Client(); $http_client->setAdapter($curl_adapter); $http_client->setUri($url); $http_client->setArgSeparator('&'); $request = new \Zend\Http\Request(); $request->setUri($url); //$http_client->setCookieJar($this->getHttpCookieJar()); // Set the token authentication $request->getHeaders()->addHeaderLine('Accept-Encoding', 'gzip,deflate'); $request->getHeaders()->addHeaderLine('Content-Type', \Zend\Http\Client::ENC_URLENCODED); if (is_array($headers)) { foreach ($headers as $key => $header) { $request->getHeaders()->addHeaderLine($key, $header); } } if ($request->getUri() === null) { throw new \Exception('No URI given. Param \'func\' is required.'); } /* @var $response Zend_Http_Response */ $response = false; if ($method == \Mojavi\Request\Request::GET) { if (is_array($params)) { $request->getQuery()->fromArray($params); } $request->setMethod(\Zend\Http\Request::METHOD_GET); $response = $http_client->send($request); } else { if ($method == \Mojavi\Request\Request::POST) { // If we uploaded files, we have to send them differently if (count($_FILES) > 0) { $request->getFiles()->fromArray($_FILES); $http_client->setEncType(\Zend\Http\Client::ENC_FORMDATA); } else { $http_client->setEncType(\Zend\Http\Client::ENC_URLENCODED); } if (is_array($params)) { $request->getPost()->fromArray($params); } $request->setMethod(\Zend\Http\Request::METHOD_POST); $response = $http_client->send($request); } else { if ($method == \Mojavi\Request\Request::DELETE) { $request->setMethod(\Zend\Http\Request::METHOD_DELETE); $response = $http_client->send($request); } else { if ($method == \Mojavi\Request\Request::PUT) { if (count($_FILES) > 0) { $request->getFiles()->fromArray($_FILES); $http_client->setEncType(\Zend\Http\Client::ENC_FORMDATA); } else { $http_client->setEncType(\Zend\Http\Client::ENC_FORMDATA); } if (is_array($params)) { $request->getQuery()->fromArray($params); } $request->setMethod(\Zend\Http\Request::METHOD_PUT); $response = $http_client->send($request); } } } } return $response; } catch (\Exception $e) { if (strpos($e->getMessage(), 'connect() timed out!') !== false && $retry_count < 3) { return $this->curl($orig_url, $params, $method, $headers, $remove_unsafe_params, ++$retry_count); } else { if (strpos($e->getMessage(), 'couldn\'t connect to host') !== false && $retry_count < 3) { return $this->curl($orig_url, $params, $method, $headers, $remove_unsafe_params, ++$retry_count); } else { if (strpos($e->getMessage(), 'Operation timed out') !== false && $retry_count < 3) { return $this->curl($orig_url, $params, $method, $headers, $remove_unsafe_params, ++$retry_count); } } } throw $e; } }
/** * 构造POST和GET组合的请求 返回相应请求 * * @param string $url * @param array $get * @param array $post * @param boolean $returnObj * @return Zend_Http_Response false */ function doRequest($url, $get = array(), $post = array(), $returnObj = false) { try { $url = trim($url); if (!filter_var($url, FILTER_VALIDATE_URL)) { throw new Exception('Invalid URL'); return false; } $client = new Zend\Http\Client(); $client->setUri($url); if (count($get) > 0 && is_array($get)) { $client->setParameterGet($get); } if (count($post) > 0 && is_array($post)) { $client->setParameterPost($post); } $client->setEncType(Zend\Http\Client::ENC_URLENCODED); $client->setOptions(array('maxredirects' => 5, 'strictredirects' => false, 'useragent' => 'Zend\\Http\\Client', 'timeout' => 10, 'adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', 'httpversion' => Request::VERSION_11, 'storeresponse' => true, 'keepalive' => false, 'outputstream' => false, 'encodecookies' => true, 'argseparator' => null, 'rfc3986strict' => false)); if (!empty($post)) { $client->setMethod(Request::METHOD_POST); } else { $client->setMethod(Request::METHOD_GET); } $response = $client->send(); return $returnObj ? $response : $response->getBody(); } catch (Exception $e) { fb(exceptionMsg($e), \FirePHP::LOG); return false; } }
// Get configuration $config = getConfig(); $token = $config['token']; // Github API token $user = $config['user']; // Your user or organization $repo = $config['repo']; // The repository you're getting the changelog for $milestone = $config['milestone']; // The milestone ID $client = new Zend\Http\Client(); $client->setOptions(array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl')); $request = $client->getRequest(); $headers = $request->getHeaders(); $headers->addHeaderLine("Authorization", "token {$token}"); $client->setUri("https://api.github.com/repos/{$user}/{$repo}/milestones/{$milestone}"); $milestoneResponseBody = $client->send()->getBody(); $milestonePayload = json_decode($milestoneResponseBody, true); if (!isset($milestonePayload['title'])) { file_put_contents('php://stderr', sprintf("Provided milestone ID [%s] does not exist: %s\n", $milestone, $milestoneResponseBody)); } $client->setUri('https://api.github.com/search/issues?q=' . urlencode('milestone:' . $milestonePayload['title'] . ' repo:' . $user . '/' . $repo . ' state:closed')); $client->setMethod('GET'); $issues = array(); $error = false; do { $response = $client->send(); $json = $response->getBody(); $payload = json_decode($json, true); if (!(is_array($payload) && isset($payload['items']))) { file_put_contents('php://stderr', sprintf("Github API returned error message [%s]\n", is_object($payload) ? $payload['message'] : $json));
/** * @throws Exception\ReceiversWasNotSpecified */ public function send() { if (!count($this->getMessages())) { throw new Exception\ReceiversWasNotSpecified(); } $client = new \Zend\Http\Client(); $client->setUri(implode('/', [self::getConfig()['uri'], 'index/send'])); $client->setHeaders(['x-auth' => self::getToken()]); $client->setMethod('POST'); $messages = []; foreach ($this->getMessages() as $message) { $messages[] = $message->asArray(); } $client->setParameterPost(['messages' => $messages]); return $client->send()->getBody(); }
<?php if (!isset($argv[1])) { die('Error require url - USAGE:$php detect.php http://example.com'); } include '../../../../vendor/autoload.php'; use Diggin\Http\Charset\Detector\HtmlDetector; // main $client = new Zend\Http\Client(); $client->setUri($argv[1]); $response = $client->send(); $detector = new HtmlDetector(); $ret = $detector->detect($response->getBody(), $response->getHeaders()->get('Content-type')->getFieldValue()); var_dump($ret);