/** * {@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()); }
/** * * @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; }
/** * Get HTTP Client. * * @return Zend\Http\Client */ public function getHttpClient() { if (!$this->httpClient) { $this->httpClient = new HttpClient(); $this->httpClient->setOptions(array('strictredirects' => true)); } return $this->httpClient; }
/** * @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); }
/** * Клиент для работы с HTTP Api. * * @return Client */ public function getClient() { if (!$this->client) { $this->client = new Client(); $this->client->setOptions(array('sslverifypeer' => false)); } return $this->client; }
public function __construct($config) { if (!isset($config['yql_base_url'])) { throw new \InvalidArgumentException('Missing yql_base_url in config'); } $this->client = new Client(); $this->client->setUri($config['yql_base_url']); $this->client->setOptions(array('maxredirects' => 0, 'timeout' => 10)); }
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); $client = new Client(); $client->setOptions($config['oauth2']['httpClient']); return $client; }
/** * @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 . ')'); } }
/** * {@inheritdoc} * @see \InoPerunApi\Client\Authenticator\ClientAuthenticatorInterface::configureClient() */ public function configureClient(Http\Client $httpClient) { $keyFile = $this->getOption(self::OPT_KEY_FILE, null, true); $crtFile = $this->getOption(self::OPT_CRT_FILE, null, true); $keyPass = $this->getOption(self::OPT_KEY_PASS); $httpClient->setOptions(array('curloptions' => array(CURLOPT_SSLKEY => $keyFile, CURLOPT_SSLCERT => $crtFile, CURLOPT_SSLKEYPASSWD => $keyPass))); }
/** * This method enables logging of requests by changing the * Zend_Http_Client_Adapter used for performing the requests. * NOTE: This will not work if you have customized the adapter * already to use a proxy server or other interface. * * @param $logfile The logfile to use when logging the requests */ public function enableRequestDebugLogging($logfile) { $this->_httpClient->setOptions(array( 'adapter' => 'Zend\GData\App\LoggingHttpClientAdapterSocket', 'logfile' => $logfile )); }
public function getServiceConfig() { return array('factories' => array('Changelog\\XmlRpc\\Client' => function ($services) { $config = $services->get('Config'); if (!isset($config['changelog'])) { throw new RuntimeException('Expecting a "changelog" key in configuration; none found'); } $config = $config['changelog']; if (!isset($config['jira']) || !is_array($config['jira'])) { throw new RuntimeException('Expecting an array of JIRA credentials in "changelog" configuration; none found'); } $jiraUrl = isset($config['jira']['url']) ? $config['jira']['url'] : 'http://framework.zend.com/issues/rpc/xmlrpc'; $cxn = new XmlRpcClient($jiraUrl); $client = $cxn->getProxy('jira1'); return $client; }, 'Changelog\\Jira\\Auth' => function ($services) { $config = $services->get('Config'); if (!isset($config['changelog'])) { throw new RuntimeException('Expecting a "changelog" key in configuration; none found'); } $config = $config['changelog']; if (!isset($config['jira']) || !is_array($config['jira'])) { throw new RuntimeException('Expecting an array of JIRA credentials in "changelog" configuration; none found'); } $jiraCredentials = $config['jira']; $client = $services->get('Changelog\\XmlRpc\\Client'); $auth = $client->login($jiraCredentials['username'], $jiraCredentials['password']); return $auth; }, 'Changelog\\Http\\Client' => function ($services) { $client = new HttpClient(); $client->setOptions(array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'keepalive' => true, 'timeout' => 10)); return $client; })); }
/** * * @param string $uri * @return \Zend\Http\Client */ protected function getHttpClient($uri) { $client = new Client(); $client->setUri($uri); $client->setOptions(['maxredirects' => 5, 'timeout' => 30])->setHeaders(['Accept-encoding' => 'gzip,deflate', 'X-Powered-By: OClient']); return $client; }
/** * Configures the client configs * * @param array $configs the http client configuration array * * @return mixed */ public function configureClientConfig(array $configs) { // We set the http client object $this->client->setOptions($configs); // We return the configured http client object return $this->client; }
public function getServiceConfig() { return array('factories' => array('Search\\GoogleCustomSearch' => function ($services) { $config = $services->get('Config'); if (!isset($config['search'])) { throw new ServiceNotFoundException(sprintf('Unable to create %s; missing configuration key "search", with subkeys "apikey" and "custom_search_identifier"', __NAMESPACE__ . '\\GoogleCustomSearch')); } $config = $config['search']; if (!isset($config['apikey']) || !is_string($config['apikey'])) { throw new ServiceNotFoundException(sprintf('Unable to create %s; missing subkey "apikey"', __NAMESPACE__ . '\\GoogleCustomSearch')); } if (!isset($config['custom_search_identifier']) || !is_string($config['custom_search_identifier'])) { throw new ServiceNotFoundException(sprintf('Unable to create %s; missing subkey "custom_search_identifier"', __NAMESPACE__ . '\\GoogleCustomSearch')); } $queryOptions = isset($config['query_options']) && is_array($config['query_options']) ? $config['query_options'] : array(); $httpClientService = isset($config['http_client_service']) && is_string($config['http_client_service']) ? $config['http_client_service'] : false; if ($httpClientService && $services->has($httpClientService)) { $httpClient = $services->get($httpClientService); } else { $httpClient = new HttpClient(); $httpClient->setOptions(array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'keepalive' => true, 'timeout' => 10)); } $search = new GoogleCustomSearch($httpClient, $config['apikey'], $config['custom_search_identifier'], $queryOptions); if (isset($config['items_per_page'])) { $search->setItemsPerPage($config['items_per_page']); } return $search; })); }
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; }
/** * 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; }
/** * @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; }
/** * Verify the user input * * @param $response * * @return Response * @throws \Exception */ public function verify($response) { if (!$this->secretKey) { throw new Exception('Missing secret key'); } $params = array('secret' => $this->secretKey, 'response' => $response); if ($this->ip !== null) { $params['ip'] = $this->ip; } $this->httpClient->setUri(self::VERIFY_SERVER); $this->httpClient->setParameterGet($params); if ($this->options) { $this->httpClient->setOptions($this->options); } $response = $this->httpClient->send(); return new CaptchaResponse($response); }
function _createHttpClient() { $adapter = new Client\Adapter\Socket(); $client = new Client(); $client->setOptions(array('maxredirects' => 2, 'strictredirects' => true)); $client->setAdapter($adapter); $adapter->setStreamContext(array('ssl' => array('capath' => '/etc/ssl/certs'))); return $client; }
/** * * @return void */ public function setUp() { if (!constant('TESTS_ZEND_SERVICE_DELICIOUS_ENABLED')) { $this->markTestSkipped('\\Zend\\Service\\Delicious online tests are not enabled'); } $httpClient = new Http\Client(); $httpClient->setOptions(array('useragent' => 'Zend\\Service\\Delicious - Unit tests/0.1', 'keepalive' => true)); $this->delicious = new Delicious\Delicious(self::TEST_UNAME, self::TEST_PASS, $httpClient); }
/** * Constructor * * Sets up the EDS API Client * * @param array $settings Associative array of setting to use in * conjunction with the EDS API * <ul> * <li>debug - boolean to control debug mode</li> * <li>authtoken - Authentication to use for calls to the API. If using IP * Authentication, this is not needed.</li> * <li>username - EBSCO username for account setup for usage with the EDS * API. This is only required for institutions using UID Authentication </li> * <li>password - EBSCO password for account setup for usage with the EDS * API. This is only required for institutions using UID Authentication </li> * <li>orgid - Organization making calls to the EDS API </li> * <li>sessiontoken - SessionToken this call is associated with, is one * exists. If not, the a profile value must be present </li> * <li>profile - EBSCO profile to use for calls to the API. </li> * <li>isguest - is the user a guest. This needs to be present if there * is no session token present</li> * </ul> * @param Zend2HttpClient $client Zend2 HTTP client object (optional) */ public function __construct($settings = [], $client = null) { parent::__construct($settings); $this->client = is_object($client) ? $client : new Zend2HttpClient(); $this->client->setOptions(['timeout' => 120]); $adapter = new CurlAdapter(); $adapter->setOptions(['curloptions' => [CURLOPT_SSL_VERIFYPEER => false, CURLOPT_FOLLOWLOCATION => true]]); $this->client->setAdapter($adapter); }
public function getHttpClient() { if ($this->httpClient) { return $this->httpClient; } $client = new Client(); $client->setUri($this->getRequestUrl()); $client->setOptions(array('maxredirects' => 0, 'sslverifypeer' => false, 'timeout' => 30)); $client->send(); return $this->httpClient = $client; }
/** * Test sending cookie header with raw value * * @group fix-double-encoding-problem-about-cookie-value */ public function testRawCookiesInRequestHeaders() { if (!constant('TESTS_ZEND_HTTP_CLIENT_ONLINE')) { $this->markTestSkipped('Zend\\Http\\Client online tests are not enabled'); } $this->_client->setOptions(array('encodecookies' => false)); $this->_client->addCookie('foo', 'bar=baz'); $this->_client->send(); $cookieValue = 'Cookie: foo=bar=baz'; $this->assertContains($cookieValue, $this->_client->getLastRawRequest(), 'Request is expected to contain the entire cookie "keyname=raw_value"'); }
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); $client = new Client(); $client->setOptions($config['oauth2']['httpClient']); $token = $serviceLocator->get('OAuth2\\Token'); if ($token->isValid()) { $client->getRequest()->getHeaders()->addHeaderLine('Authorization', "{$token->getTokenType()} {$token->getAccessToken()}"); } return $client; }
/** * Sends the HTTP request and returns the response. * * @param Http\Request $httpRequest * @throws HttpClientException * @return Http\Response */ public function sendHttpRequest(Http\Request $httpRequest) { $this->setLastHttpRequest($httpRequest); $this->httpClient->setOptions($this->options->get(self::OPT_HTTP_OPTIONS, array())); try { $httpResponse = $this->httpClient->send($httpRequest); } catch (\Exception $e) { throw new HttpClientException(sprintf("Exception during HTTP request: [%s] %s", get_class($e), $e->getMessage())); } $this->setLastHttpResponse($httpResponse); return $httpResponse; }
/** * Test we can properly redirect to a relative path * */ public function testRelativePathRedirect() { $this->client->setUri($this->baseuri . 'testRelativeRedirections.php'); $this->client->setParameterGet(array('redirect' => 'relpath')); $this->client->setOptions(array('maxredirects' => 1)); // Set the new expected URI $uri = clone $this->client->getUri(); $uri->setPath(rtrim(dirname($uri->getPath()), '/') . '/path/to/fake/file.ext'); $uri = $uri->__toString(); $res = $this->client->send(); $this->assertEquals("{$uri}?redirect=relpath", $this->client->getUri()->toString(), "The new location is not as expected: {$this->client->getUri()->toString()}"); }
private function search($query, $geolocate = false, $start = 1) { $query = urlencode($query); $client = new Client(); $client->setOptions(['timeout' => 60]); $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl'); $client->setUri('https://www.googleapis.com/customsearch/v1'); $searchParams = $geolocate ? ['key' => GOOGLE_SEARCH_API_KEY, 'cx' => GOOGLE_SEARCH_CSE_ID, 'q' => $query, 'cr' => 'countryCL', 'gl' => 'cl', 'hl' => 'es', 'googlehost' => 'google.cl', 'start' => $start] : ['key' => GOOGLE_SEARCH_API_KEY, 'cx' => GOOGLE_SEARCH_CSE_ID, 'q' => $query, 'start' => $start]; $client->setParameterGet($searchParams); $response = $client->send(); return $response->isSuccess() ? json_decode($response->getBody()) : null; }
public static function nearby($countryCode, $postalCode) { $http = new Client(); $http->setOptions(array('sslverifypeer' => false)); $headers = new Headers(); $headers->addHeaderLine('Content-Type', 'application/json'); $http->setHeaders($headers); $http->setUri(self::$apiUrl . 'nearby/' . urlencode($countryCode) . '/' . urlencode($postalCode)); $http->setMethod('GET'); $response = $http->send(); $json = Json::decode($response->getBody()); return $json; }
private function search($query, $geolocate) { $query = urlencode($query); $client = new Client(); $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl'); $client->setOptions(['timeout' => 60]); $client->setAuth(BING_SEARCH_API_KEY, BING_SEARCH_API_KEY); $client->setUri('https://api.datamarket.azure.com/Bing/Search/v1/Web'); $searchParams = $geolocate ? ['Market' => "'es-Cl'", 'Latitude' => '-33.45', 'Longitude' => '-70.6667', 'Query' => "'{$query}'", '$format' => 'json'] : ['Query' => "'{$query}'", '$format' => 'json']; $client->setParameterGet($searchParams); $response = $client->send(); return $response->isSuccess() ? json_decode($response->getBody()) : null; }
/** * @param \SMS\Model\Number $from * @param \SMS\Model\Number $to * @param \SMS\Model\Content $content * @return bool * @throws \SMS\SMSException * @throws \Exception */ public function send(Number $from, Number $to, Content $content) { $client = new Client(); $client->setUri($this->prepareUrl($from, $to, $content)); $client->setMethod('GET'); $client->setOptions(array('ssltransport' => 'tls', 'sslverify_peer' => false, 'sslcapath' => '/etc/ssl/certs')); $response = $client->send($client->getRequest()); $responsejson = json_decode($response->getContent()); if ($responsejson->status != 100) { throw new SMSException($response); } return true; }