public function testIfCookiesAreSticky() { $initialCookies = array( new SetCookie('foo', 'far', null, '/', 'www.domain.com' ), new SetCookie('bar', 'biz', null, '/', 'www.domain.com') ); $requestString = "GET http://www.domain.com/index.php HTTP/1.1\r\nHost: domain.com\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) Gecko/20100101 Firefox/16.0\r\nAccept: */*\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n"; $request = Request::fromString($requestString); $client = new Client('http://www.domain.com/'); $client->setRequest($request); $client->addCookie($initialCookies); $cookies = new Cookies($client->getRequest()->getHeaders()); $rawHeaders = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Encoding: gzip\r\nContent-Type: application/javascript\r\nDate: Sun, 18 Nov 2012 16:16:08 GMT\r\nServer: nginx/1.1.19\r\nSet-Cookie: baz=bah; domain=www.domain.com; path=/\r\nSet-Cookie: joe=test; domain=www.domain.com; path=/\r\nVary: Accept-Encoding\r\nX-Powered-By: PHP/5.3.10-1ubuntu3.4\r\nConnection: keep-alive\r\n"; $response = Response::fromString($rawHeaders); $client->setResponse($response); $cookies->addCookiesFromResponse($client->getResponse(), $client->getUri()); $client->addCookie( $cookies->getMatchingCookies($client->getUri()) ); $this->assertEquals(4, count($client->getCookies())); }
protected function _replace($filePath, $photoId, $async = 0) { $params['async'] = $async; $params['photo_id'] = $photoId; $finalParams = $this->_httpUtility->assembleParams($this->_endpointReplace, $this->_configOAuth, $params); $request = new \Zend\Http\Request(); $request->setUri($this->_endpointReplace)->setMethod('POST')->setPost(new Parameters($finalParams)); $this->_httpClient->reset(); $this->_httpClient->setRequest($request); $this->_httpClient->setEncType(\Zend\Http\Client::ENC_FORMDATA, 'ITSCARO'); $this->_httpClient->setFileUpload($filePath, 'photo'); $response = $this->_httpClient->dispatch($request); $decodedResponse = simplexml_load_string($response->getBody()); if (!$decodedResponse instanceof \SimpleXMLElement) { throw new \Exception('Could not decode response: ' . $response->getBody(), self::ERR_RESPONSE_NOT_XML); } else { if ($decodedResponse['stat'] == 'ok') { if ($async) { return (string) $decodedResponse->ticketid; } else { return (string) $decodedResponse->photoid; } } else { throw new \Exception((string) $decodedResponse->err['msg'], (int) $decodedResponse->err['code']); } } }
public function callServer($method, $params) { // Get the URI and Url Elements $apiUrl = $this->generateUrl($method); $requestUri = $apiUrl['uri']; // Convert the params to something MC can understand $params = $this->processParams($params); $params["apikey"] = $this->getConfig('apiKey'); $request = new Request(); $request->setMethod(Request::METHOD_POST); $request->setUri($requestUri); $request->getHeaders()->addHeaders(array('Host' => $apiUrl['host'], 'User-Agent' => 'MCAPI/' . $this->getConfig('apiVersion'), 'Content-type' => 'application/x-www-form-urlencoded')); $client = new Client(); $client->setRequest($request); $client->setParameterPost($params); $result = $client->send(); if ($result->getHeaders()->get('X-MailChimp-API-Error-Code')) { $error = unserialize($result->getBody()); if (isset($error['error'])) { throw new MailchimpException('The mailchimp API has returned an error (' . $error['code'] . ': ' . $error['error'] . ')'); return false; } else { throw new MailchimpException('There was an unspecified error'); return false; } } return $result->getBody(); }
public function testAcceptEncodingHeaderWorksProperly() { $method = new \ReflectionMethod('\\Zend\\Http\\Client', 'prepareHeaders'); $method->setAccessible(true); $requestString = "GET http://www.domain.com/index.php HTTP/1.1\r\nHost: domain.com\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) Gecko/20100101 Firefox/16.0\r\nAccept: */*\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n"; $request = Request::fromString($requestString); $adapter = new \Zend\Http\Client\Adapter\Test(); $client = new \Zend\Http\Client('http://www.domain.com/'); $client->setAdapter($adapter); $client->setRequest($request); $rawHeaders = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Encoding: gzip, deflate\r\nContent-Type: application/javascript\r\nDate: Sun, 18 Nov 2012 16:16:08 GMT\r\nServer: nginx/1.1.19\r\nVary: Accept-Encoding\r\nX-Powered-By: PHP/5.3.10-1ubuntu3.4\r\nConnection: keep-alive\r\n"; $response = Response::fromString($rawHeaders); $client->getAdapter()->setResponse($response); $headers = $method->invoke($client, $requestString, $client->getUri()); $this->assertEquals('gzip, deflate', $headers['Accept-Encoding']); }
/** * Prepare a POST request for uploading files * * The request method will be set to POST and multipart/form-data will be used * as content type, ignoring the current request format. * * $files is treated as: * [ * name => localFilePath, * ... * ] * * $data will be used for other data data without the filename segment. * * Each localFilePath will be read and sent. Will try to guess the content type using mime_content_type(). * By default, the basename of localFilePath will be sent as filename segment, if a 'name' is also present * in $data then the value of $data[name] will be used as filename segment. * * * * @param array $files * @param string $relativePath * @param array $data * @param array $query * @return \Zend\Http\Request */ public function prepareFileUploadRequest(array $files, $relativePath = null, array $data = [], array $query = []) { $request = $this->prepareRequest('POST', $relativePath, [], $query); $request->getHeaders()->removeHeader($request->getHeaders()->get('Content-Type')); $this->httpClient->setRequest($request); foreach ($files as $formName => $filePath) { $this->httpClient->setFileUpload($filePath, $formName); if (isset($data[$formName])) { $file = $request->getFiles()->get($filePath, null); if ($file) { // If present, override the filename $file['filename'] = $data[$formName]; $request->getFiles()->set($filePath, $file); } unset($data[$formName]); } } $request->getPost()->fromArray($data); return $request; }
/** * Get the latest version from Github. * * @param Http\Client $httpClient Configured HTTP client * * @return string|null API response or false on error */ protected static function getLatestFromGithub(Http\Client $httpClient = null) { $url = 'https://api.github.com/repos/iteaoffice/calendar/git/refs/tags/release-'; if ($httpClient === null) { $context = stream_context_create(['http' => ['user_agent' => sprintf('iteaoffice-version/%s', self::VERSION)]]); $apiResponse = file_get_contents($url, false, $context); } else { $request = new Http\Request(); $request->setUri($url); $httpClient->setRequest($request); $apiResponse = self::getApiResponse($httpClient); } if (!$apiResponse) { return false; } $decodedResponse = Json::decode($apiResponse, Json::TYPE_ARRAY); // Simplify the API response into a simple array of version numbers $tags = array_map(function ($tag) { return substr($tag['ref'], 18); // Reliable because we're // filtering on 'refs/tags/release-' }, $decodedResponse); // Fetch the latest version number from the array return array_reduce($tags, function ($a, $b) { return version_compare($a, $b, '>') ? $a : $b; }); }
/** * Get the latest version from framework.zend.com * * @param Http\Client $httpClient Configured HTTP client * @return string|null API response or false on error */ protected static function getLatestFromZend(Http\Client $httpClient = null) { $url = 'http://framework.zend.com/api/zf-version?v=2'; if ($httpClient === null) { $apiResponse = file_get_contents($url); } else { $request = new Http\Request(); $request->setUri($url); $httpClient->setRequest($request); $apiResponse = self::getApiResponse($httpClient); } if (!$apiResponse) { return false; } return $apiResponse; }
/** * Get the latest version from Github * * @param Http\Client $httpClient Configured HTTP client * * @return string|null API response or false on error */ protected static function getLatestFromGithub(Http\Client $httpClient = null) { $url = 'https://api.github.com/repos/debranova/contact/git/refs/tags/release-'; $url .= '?client_id=2b1088587b9820f33583&client_secret=1738809f67b3fbf4198f2bc36ef54c52d6a3bb6c'; if ($httpClient === null) { $context = stream_context_create(array('http' => array('user_agent' => sprintf('debranova-version/%s', self::VERSION)))); $apiResponse = file_get_contents($url, false, $context); } else { $request = new Http\Request(); $request->setUri($url); $httpClient->setRequest($request); $apiResponse = self::getApiResponse($httpClient); } if (!$apiResponse) { return false; } $decodedResponse = Json::decode($apiResponse, Json::TYPE_ARRAY); // Simplify the API response into a simple array of version numbers $tags = array_map(function ($tag) { return substr($tag['ref'], 18); // Reliable because we're // filtering on 'refs/tags/release-' }, $decodedResponse); // Fetch the latest version number from the array return array_reduce($tags, function ($a, $b) { return version_compare($a, $b, '>') ? $a : $b; }); }
/** * Initiate an HTTP GET request * This is used to request a list of data. * Where get params are specified, it normally returns data for a specific entity * @param array $arr_request_params - optional * @return Ambigous <\FrontCore\Models\ApiRequestModel, \FrontCore\Models\ApiRequestModel> */ public function performGETRequest($arr_request_params = NULL) { if (is_object($arr_request_params) && $arr_request_params instanceof \Zend\Stdlib\ArrayObject) { $arr_request_params = $arr_request_params->getArrayCopy(); } //end if //load user session data $objUserSession = FrontUserSession::isLoggedIn(); //configure the request and client $request = new Request(); $request->setUri(self::buildURI()); $request->setMethod(Request::METHOD_GET); $client = new Client(); $client->setRequest($request); //set GET params if any if (is_array($arr_request_params)) { $client->setParameterGet($arr_request_params); } //end if //execute return self::executeRequest($client, $request); }
public function testPrepareHeadersCreateRightHttpField() { $body = json_encode(array('foofoo' => 'barbar')); $client = new Client(); $prepareHeadersReflection = new \ReflectionMethod($client, 'prepareHeaders'); $prepareHeadersReflection->setAccessible(true); $request = new Request(); $request->getHeaders()->addHeaderLine('content-type', 'application/json'); $request->getHeaders()->addHeaderLine('content-length', strlen($body)); $client->setRequest($request); $client->setEncType('application/json'); $this->assertSame($client->getRequest(), $request); $headers = $prepareHeadersReflection->invoke($client, $body, new Http('http://localhost:5984')); $this->assertArrayNotHasKey('content-type', $headers); $this->assertArrayHasKey('Content-Type', $headers); $this->assertArrayNotHasKey('content-length', $headers); $this->assertArrayHasKey('Content-Length', $headers); }