/** * 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; }
/** * Return the singleton instance of the HTTP Client. Note that * the instance is reset and cleared of previous parameters GET/POST. * Headers are NOT reset but handled by this component if applicable. * * @return Http\Client */ public static function getHttpClient() { if (!isset(static::$httpClient)) { static::$httpClient = new Http\Client(); } else { static::$httpClient->resetParameters(); } return static::$httpClient; }
/** * Return the singleton instance of the HTTP Client. Note that * the instance is reset and cleared of previous parameters and * Authorization header values. * * @return Zend\Http\Client */ public static function getHttpClient() { if (!isset(self::$httpClient)) { self::$httpClient = new HTTPClient(); } else { self::$httpClient->setHeaders('Authorization', null); self::$httpClient->resetParameters(); } return self::$httpClient; }
/** * {@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())); }
/** * {@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())); }
/** * Return the singleton instance of the HTTP Client. Note that * the instance is reset and cleared of previous parameters and * Authorization header values. * * @return Zend\Http\Client */ public static function getHttpClient() { if (!isset(self::$httpClient)) { self::$httpClient = new HTTPClient(); } else { $request = self::$httpClient->getRequest(); $headers = $request->getHeaders(); if ($headers->has('Authorization')) { $auth = $headers->get('Authorization'); $headers->removeHeader($auth); } self::$httpClient->resetParameters(); } return self::$httpClient; }
/** * 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; }
/** * 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(); }
/** * @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); }
/** * Make sure we can reset the parameters between consecutive requests * */ public function testResetParameters() { $params = array( 'quest' => 'To seek the holy grail', 'YourMother' => 'Was a hamster', 'specialChars' => '<>$+ &?=[]^%', 'array' => array('firstItem', 'secondItem', '3rdItem') ); $headers = array("X-Foo" => "bar"); $this->client->setParameterPost($params); $this->client->setParameterGet($params); $this->client->setHeaders($headers); $this->client->setMethod('POST'); $res = $this->client->send(); $this->assertContains(serialize($params) . "\n" . serialize($params), $res->getBody(), "returned body does not contain all GET and POST parameters (it should!)"); $this->client->resetParameters(); $this->client->setMethod('POST'); $res = $this->client->send(); $this->assertNotContains(serialize($params), $res->getBody(), "returned body contains GET or POST parameters (it shouldn't!)"); $headerXFoo= $this->client->getHeader("X-Foo"); $this->assertTrue(empty($headerXFoo), "Header not preserved by reset"); }
/** * Return the singleton instance of the HTTP Client. Note that * the instance is reset and cleared of previous parameters GET/POST. * Headers are NOT reset but handled by this component if applicable. * * @return \Zend\Http\Client */ public static function getHttpClient() { if (!isset(self::$httpClient)): self::$httpClient = new Http\Client; else: self::$httpClient->resetParameters(); endif; return self::$httpClient; }
/** * Sends a request. * * @param string $url The url. * @param string $method The http method. * @param array $headers The headers. * @param array $content The content. * @param array $files The files. * * @throws \Widop\HttpAdapter\HttpAdapterException If an error occured. * * @return \Widop\HttpAdapter\HttpResponse The response. */ private function sendRequest($url, $method, array $headers = array(), array $content = array(), array $files = array()) { $this->client->resetParameters()->setOptions(array('maxredirects' => $this->getMaxRedirects()))->setMethod($method)->setUri($url)->setHeaders($headers)->setParameterPost($content); foreach ($files as $key => $file) { $this->client->setFileUpload($file, $key); } try { $response = $this->client->send(); } catch (\Exception $e) { throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage()); } return $this->createResponse($response->getStatusCode(), $url, $response->getHeaders()->toArray(), $method === Request::METHOD_HEAD ? '' : $response->getBody()); }
/** * Perform a single OAI-PMH request. * * @param string $verb OAI-PMH verb to execute. * @param array $params GET parameters for ListRecords method. * * @return string */ protected function sendRequest($verb, $params) { // Set up the request: $this->client->resetParameters(); $this->client->setUri($this->baseUrl); // Load request parameters: $query = $this->client->getRequest()->getQuery(); $query->set('verb', $verb); foreach ($params as $key => $value) { $query->set($key, $value); } // Perform request: return $this->client->setMethod('GET')->send(); }
/** * Retrieve a specific record. * * @param string $id Record ID to retrieve * @param ParamBag $params Parameters * * @throws \Exception * @return array */ public function getRecord($id, ParamBag $params = null) { $query = "AN " . $id; $params = $params ?: new ParamBag(); $params->set('prof', $this->prof); $params->set('pwd', $this->pwd); $params->set('query', $query); $this->client->resetParameters(); $response = $this->call('GET', $params->getArrayCopy(), false); $xml = simplexml_load_string($response); $finalDocs = []; foreach ($xml->SearchResults->records->rec as $doc) { $finalDocs[] = simplexml_load_string($doc->asXML()); } return ['docs' => $finalDocs, 'offset' => 0, 'total' => (int) $xml->Hits]; }
/** * Small wrapper for sendRequest, process to simplify error handling. * * @param string $qs Query string * @param string $method HTTP method * * @return object The parsed primo data * @throws \Exception */ protected function call($qs, $method = 'GET') { $this->debug("{$method}: {$this->host}{$qs}"); $this->client->resetParameters(); if ($method == 'GET') { $baseUrl = $this->host . $qs; } elseif ($method == 'POST') { throw new \Exception('POST not supported'); } // Send Request $this->client->setUri($baseUrl); $result = $this->client->setMethod($method)->send(); if (!$result->isSuccess()) { throw new \Exception($result->getBody()); } return $this->process($result->getBody()); }
/** * Make an OAI-PMH request. Die if there is an error; return a SimpleXML object * on success. * * @param string $verb OAI-PMH verb to execute. * @param array $params GET parameters for ListRecords method. * * @return object SimpleXML-formatted response. */ protected function sendRequest($verb, $params = []) { // Debug: if ($this->verbose) { $this->write("Sending request: verb = {$verb}, params = " . print_r($params, true)); } // Set up retry loop: while (true) { // Set up the request: $this->client->resetParameters(); $this->client->setUri($this->baseURL); $this->client->setOptions(['timeout' => $this->timeout]); // Set authentication, if necessary: if ($this->httpUser && $this->httpPass) { $this->client->setAuth($this->httpUser, $this->httpPass); } // Load request parameters: $query = $this->client->getRequest()->getQuery(); $query->set('verb', $verb); foreach ($params as $key => $value) { $query->set($key, $value); } // Perform request and die on error: $result = $this->client->setMethod('GET')->send(); if ($result->getStatusCode() == 503) { $delayHeader = $result->getHeaders()->get('Retry-After'); $delay = is_object($delayHeader) ? $delayHeader->getDeltaSeconds() : 0; if ($delay > 0) { if ($this->verbose) { $this->writeLine("Received 503 response; waiting {$delay} seconds..."); } sleep($delay); } } else { if (!$result->isSuccess()) { throw new \Exception('HTTP Error'); } else { // If we didn't get an error, we can leave the retry loop: break; } } } // If we got this far, there was no error -- send back response. return $this->processResponse($result->getBody()); }
/** * Perform an HTTP request. * * @param string $baseUrl Base URL for request * @param string $method HTTP method for request * @param string $queryString Query string to append to URL * @param array $headers HTTP headers to send * * @throws SerialsSolutions_Summon_Exception * @return string HTTP response body */ protected function httpRequest($baseUrl, $method, $queryString, $headers) { $this->debugPrint("{$method}: {$baseUrl}?{$queryString}"); $this->client->resetParameters(); if ($method == 'GET') { $baseUrl .= '?' . $queryString; } elseif ($method == 'POST') { $this->client->setRawBody($queryString, 'application/x-www-form-urlencoded'); } $this->client->setHeaders($headers); // Send Request $this->client->setUri($baseUrl); $result = $this->client->setMethod($method)->send(); if (!$result->isSuccess()) { throw new SerialsSolutions_Summon_Exception($result->getBody()); } return $result->getBody(); }
/** * Call a remote REST web service URI * * @param string $path The path to append to the URI * @throws Client\Exception\UnexpectedValueException * @return void */ protected function prepare($path) { // Get the URI object and configure it if (!$this->uri instanceof Uri\Uri) { throw new Exception\UnexpectedValueException('URI object must be set before performing call'); } $uri = $this->uri->toString(); if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') { $path = '/' . $path; } $this->uri->setPath($path); /** * Get the HTTP client and configure it for the endpoint URI. * Do this each time because the Zend\Http\Client instance is shared * among all Zend_Service_Abstract subclasses. */ $this->localHttpClient->resetParameters()->setUri((string) $this->uri); }
/** * Perform an HTTP request. * * @param string $baseUrl Base URL for request * @param string $method HTTP method for request (GET,POST, etc.) * @param string $queryString Query string to append to URL * @param array $headers HTTP headers to send * @param string $messageBody Message body to for HTTP Request * @param string $messageFormat Format of request $messageBody and respones * * @throws EbscoEdsApiException * @return string HTTP response body */ protected function httpRequest($baseUrl, $method, $queryString, $headers, $messageBody = null, $messageFormat = "application/json; charset=utf-8") { $this->debugPrint("{$method}: {$baseUrl}?{$queryString}"); $this->client->resetParameters(); $this->client->setHeaders($headers); $this->client->setMethod($method); if ($method == 'GET' && !empty($queryString)) { $baseUrl .= '?' . $queryString; } elseif ($method == 'POST' && isset($messageBody)) { $this->client->setRawBody($messageBody); } $this->client->setUri($baseUrl); $this->client->setEncType($messageFormat); $result = $this->client->send(); if (!$result->isSuccess()) { throw new \EbscoEdsApiException(json_decode($result->getBody(), true)); } return $result->getBody(); }
/** * Clear all custom parameters we set. * * @return Zend\Http\Client */ public function resetParameters($clearAll = false) { $this->_streamingRequest = false; return parent::resetParameters($clearAll); }
/** * Perform request using Client channel * * @param string $path Path * @param string $queryString Query string * @param string $httpVerb HTTP verb the request will use * @param array $headers x-ms headers to add * @param boolean $forTableStorage Is the request for table storage? * @param mixed $rawData Optional RAW HTTP data to be sent over the wire * @param string $resourceType Resource type * @param string $requiredPermission Required permission * @return Response */ protected function _performRequest( $path = '/', $queryString = '', $httpVerb = Request::METHOD_GET, $headers = array(), $forTableStorage = false, $rawData = null, $resourceType = Storage::RESOURCE_UNKNOWN, $requiredPermission = Credentials\AbstractCredentials::PERMISSION_READ ) { // Clean path if (strpos($path, '/') !== 0) { $path = '/' . $path; } // Clean headers if ($headers === null) { $headers = array(); } // Ensure cUrl will also work correctly: // - disable Content-Type if required // - disable Expect: 100 Continue if (!isset($headers["Content-Type"])) { $headers["Content-Type"] = ''; } $headers["Expect"] = ''; // Add version header $headers['x-ms-version'] = $this->_apiVersion; // URL encoding $path = self::urlencode($path); $queryString = self::urlencode($queryString); // Generate URL and sign request $requestUrl = $this->_credentials ->signRequestUrl($this->getBaseUrl() . $path . $queryString, $resourceType, $requiredPermission); $requestHeaders = $this->_credentials ->signRequestHeaders($httpVerb, $path, $queryString, $headers, $forTableStorage, $resourceType, $requiredPermission); // Prepare request $this->_httpClientChannel->resetParameters(true); $this->_httpClientChannel->setUri($requestUrl); $this->_httpClientChannel->setHeaders($requestHeaders); $this->_httpClientChannel->setRawBody($rawData); // Execute request $response = $this->_retryPolicy->execute( array($this->_httpClientChannel, 'request'), array($httpVerb) ); return $response; }
/** * Returns the instance of the Zend\Http\Client which will be used. Creates an instance * of Zend\Http\Client if no previous client was set. * * @return Zend\Http\Client The HTTP client which will be used */ public function getHttpClient() { if (!$this->httpclient instanceof Http\Client) { $client = new Http\Client(); $client->setConfig(array('maxredirects' => 2, 'timeout' => 5)); $this->setHttpClient($client); } $this->httpclient->resetParameters(); return $this->httpclient; }
/** * Call a remote REST web service URI * * @param string $path The path to append to the URI * @param Http\Client $client * @throws Client\Exception\UnexpectedValueException * @return void */ protected function prepare($path, Http\Client $client) { $client->setUri(static::API_BASE_URI . $path . '.json'); /** * Do this each time to ensure oauth calls do not inject new params */ $client->resetParameters(); }
/** * 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 HttpClient($url, array('maxredirects' => 4, 'timeout' => 15, 'useragent' => 'Zend_OpenId')); } else { $client->setUri($url); } $client->resetParameters(); if ($method == Request::METHOD_POST) { $client->setMethod(Request::METHOD_POST); $client->setParameterPost($params); } else { $client->setMethod(Request::METHOD_GET); $client->setParameterGet($params); } try { $response = $client->send(); } catch (\Exception $e) { $this->_setError('HTTP Request failed: ' . $e->getMessage()); return false; } $status = $response->getStatusCode(); $body = $response->getBody(); if ($status == 200 || $status == 400 && !empty($body)) { return $body; } else { $this->_setError('Bad HTTP response'); return false; } }
/** * Get clean Http client * * @param string $url URL * @param string $method Method * * @return Client */ protected function _getCleanHttpClient($url, $method = Request::METHOD_GET) { $client = new Client($url); return $client->resetParameters(true)->setMethod($method)->setAdapter(self::CONNECTION_CURL_ADAPTER); }
/** * Performs a HTTP request using the specified method * * @param string $method The HTTP method for the request - 'GET', 'POST', * 'PUT', 'DELETE' * @param string $url The URL to which this request is being performed * @param array $headers An associative array of HTTP headers * for this request * @param string $body The body of the HTTP request * @param string $contentType The value for the content type * of the request body * @param int $remainingRedirects Number of redirects to follow if request * s results in one * @return \Zend\Http\Response The response object */ public function performHttpRequest($method, $url, $headers = null, $body = null, $contentType = null, $remainingRedirects = null) { if ($remainingRedirects === null) { $remainingRedirects = self::getMaxRedirects(); } if ($headers === null) { $headers = array(); } // Append a Gdata version header if protocol v2 or higher is in use. // (Protocol v1 does not use this header.) $major = $this->getMajorProtocolVersion(); $minor = $this->getMinorProtocolVersion(); if ($major >= 2) { $headers['GData-Version'] = $major + ($minor === null ? '.' + $minor : ''); } // check the overridden method if (($method == 'POST' || $method == 'PUT') && $body === null && $headers['x-http-method-override'] != 'DELETE') { throw new App\InvalidArgumentException('You must specify the data to post as either a ' . 'string or a child of Zend\\GData\\App\\Entry'); } if ($url === null) { throw new App\InvalidArgumentException('You must specify an URI to which to post.'); } $headers['Content-Type'] = $contentType; if (self::getGzipEnabled()) { // some services require the word 'gzip' to be in the user-agent // header in addition to the accept-encoding header if (strpos($this->_httpClient->getHeader('User-Agent'), 'gzip') === false) { $headers['User-Agent'] = $this->_httpClient->getHeader('User-Agent') . ' (gzip)'; } $headers['Accept-encoding'] = 'gzip, deflate'; } else { $headers['Accept-encoding'] = 'identity'; } // Make sure the HTTP client object is 'clean' before making a request // In addition to standard headers to reset via resetParameters(), // also reset the Slug and If-Match headers $this->_httpClient->resetParameters(); $this->_httpClient->setHeaders(array('Slug', 'If-Match')); // Set the params for the new request to be performed $this->_httpClient->setHeaders($headers); $urlObj = new \Zend\Uri\Url($url); preg_match("/^(.*?)(\\?.*)?\$/", $url, $matches); $this->_httpClient->setUri($matches[1]); $queryArray = $urlObj->getQueryAsArray(); foreach ($queryArray as $name => $value) { $this->_httpClient->setParameterGet($name, $value); } $this->_httpClient->setConfig(array('maxredirects' => 0)); // Set the proper adapter if we are handling a streaming upload $usingMimeStream = false; $oldHttpAdapter = null; if ($body instanceof \Zend\GData\MediaMimeStream) { $usingMimeStream = true; $this->_httpClient->setRawDataStream($body, $contentType); $oldHttpAdapter = $this->_httpClient->getAdapter(); if ($oldHttpAdapter instanceof \Zend\Http\Client\Adapter\Proxy) { $newAdapter = new HttpAdapterStreamingProxy(); } else { $newAdapter = new HttpAdapterStreamingSocket(); } $this->_httpClient->setAdapter($newAdapter); } else { $this->_httpClient->setRawData($body, $contentType); } try { $response = $this->_httpClient->request($method); // reset adapter if ($usingMimeStream) { $this->_httpClient->setAdapter($oldHttpAdapter); } } catch (\Zend\Http\Client\Exception $e) { // reset adapter if ($usingMimeStream) { $this->_httpClient->setAdapter($oldHttpAdapter); } throw new App\HttpException($e->getMessage(), $e); } if ($response->isRedirect() && $response->getStatus() != '304') { if ($remainingRedirects > 0) { $newUrl = $response->getHeader('Location'); $response = $this->performHttpRequest($method, $newUrl, $headers, $body, $contentType, $remainingRedirects); } else { throw new App\HttpException('Number of redirects exceeds maximum', null, $response); } } if (!$response->isSuccessful()) { $exceptionMessage = 'Expected response code 200, got ' . $response->getStatus(); if (self::getVerboseExceptionMessages()) { $exceptionMessage .= "\n" . $response->getBody(); } $exception = new App\HttpException($exceptionMessage); $exception->setResponse($response); throw $exception; } return $response; }
/** * * @param string $url * @return insatnce of Zend\Http\Client */ protected function getNewResponse($url = NULL) { $client = new HttpClient(); /** * Incase of 2nd call , use product url */ if ($url != NULL) { $client->setUri($url); } /** * check if it is 2nd call then use the header cookies so that we can use the same session to avoid */ /** * sending more traffic to the site for the performance point of view */ if (isset($_SESSION['cookiejar']) && $_SESSION['cookiejar'] instanceof \Zend\Http\Cookies) { $cookieJar = $_SESSION['cookiejar']; } else { // set Curl Adapter $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl'); // $response = $this->getResponse (); // keep the conntection alive for multiple calls $client->setOptions(array('keepalive' => true)); // set content-type // $httpResponse->getHeaders ()->addHeaderLine ( 'content-type', 'text/html; charset=utf-8' ); $client->setUri(SELF::GROCCERYURL); $result = $client->send(); $cookieJar = \Zend\Http\Cookies::fromResponse($result, SELF::GROCCERYURL); $_SESSION['cookiejar'] = $cookieJar; $client->resetParameters(); return $result; } $connectionCookies = $cookieJar->getMatchingCookies($client->getUri()); // set the cookies for the 2nd call $client->setCookies($this->getConntetionCookies($connectionCookies)); $response = $client->send(); return $response; }