/** * Create a new instance of the Client if we don't have it or * return the one we already have to reuse * * @return Client */ protected static function getClientInstance() { if (self::$client === null) { self::$client = new Client(); self::$client->setEncType(Client::ENC_URLENCODED); } return self::$client; }
/** * Add a new subscription * * @return JsonModel */ public function create($data) { $username = $this->params()->fromRoute('username'); $usersTable = $this->getTable('UsersTable'); $user = $usersTable->getByUsername($username); $userFeedsTable = $this->getTable('UserFeedsTable'); $rssLinkXpath = '//link[@type="application/rss+xml"]'; $faviconXpath = '//link[@rel="shortcut icon"]'; $client = new Client($data['url']); $client->setEncType(Client::ENC_URLENCODED); $client->setMethod(\Zend\Http\Request::METHOD_GET); $response = $client->send(); if ($response->isSuccess()) { $html = $response->getBody(); $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"); $dom = new Query($html); $rssUrl = $dom->execute($rssLinkXpath); if (!count($rssUrl)) { throw new Exception('Rss url not found in the url provided', 404); } $rssUrl = $rssUrl->current()->getAttribute('href'); $faviconUrl = $dom->execute($faviconXpath); if (count($faviconUrl)) { $faviconUrl = $faviconUrl->current()->getAttribute('href'); } else { $faviconUrl = null; } } else { throw new Exception("Website not found", 404); } $rss = Reader::import($rssUrl); return new JsonModel(array('result' => $userFeedsTable->create($user->id, $rssUrl, $rss->getTitle(), $faviconUrl))); }
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; }
/** * Sets a proper EncType on the given \Zend\Http\Client object (for Xml Request, used value is Client::ENC_URLENCODED) * * @param \Zend\Http\Client $client the Zend http client object * * @return mixed|\Zend\Http\Client */ public function setClientEncType(\Zend\Http\Client $client) { // Setting EncType to UrlEncoded //TODO is it really necessary? xml request should just send some xml code in the body; thus, no need for encryption $client->setEncType(\Zend\Http\Client::ENC_URLENCODED); return $client; }
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']); } } }
/** * @param string $method * @param string $url * @param array [optional] $params */ public function request($method, $url, $params = []) { $this->httpClient->setUri($this->moduleOptions->getApiUrl() . '/' . ltrim($url, '/')); $this->httpClient->setMethod($method); if (!is_null($params)) { if ($method == 'post' || $method == 'put') { $this->httpClient->setEncType(HttpClient::ENC_FORMDATA); $this->httpClient->setParameterPost($params); } else { $this->httpClient->setEncType(HttpClient::ENC_URLENCODED); $this->httpClient->setParameterGet($params); } } $response = $this->httpClient->send(); $data = json_decode($response->getBody(), true); return $data; }
/** * Write a message to the log. * * @param array $event event data * * @return void * @throws \Zend\Log\Exception\RuntimeException */ protected function doWrite(array $event) { // Apply verbosity filter: if (is_array($event['message'])) { $event['message'] = $event['message'][$this->verbosity]; } // Create request $this->client->setUri($this->url); $this->client->setMethod('POST'); $this->client->setEncType($this->contentType); $this->client->setRawBody($this->getBody($this->applyVerbosity($event))); // Send $response = $this->client->send(); }
public function testStreamRequest() { if (!$this->client->getAdapter() instanceof Adapter\StreamInterface) { $this->markTestSkipped('Current adapter does not support streaming'); return; } $data = fopen(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'staticFile.jpg', "r"); $this->client->setRawBody($data); $this->client->setEncType('image/jpeg'); $this->client->setMethod('PUT'); $res = $this->client->send(); $expected = $this->_getTestFileContents('staticFile.jpg'); $this->assertEquals($expected, $res->getBody(), 'Response body does not contain the expected data'); }
/** * Test that we properly calculate the content-length of multibyte-encoded * request body * * This may file in case that mbstring overloads the substr and strlen * functions, and the mbstring internal encoding is a multibyte encoding. * * @link http://framework.zend.com/issues/browse/ZF-2098 */ public function testMultibyteRawPostDataZF2098() { $this->_client->setAdapter('Zend\\Http\\Client\\Adapter\\Test'); $this->_client->setUri('http://example.com'); $bodyFile = __DIR__ . '/_files/ZF2098-multibytepostdata.txt'; $this->_client->setRawBody(file_get_contents($bodyFile)); $this->_client->setEncType('text/plain'); $this->_client->setMethod('POST'); $this->_client->send(); $request = $this->_client->getLastRawRequest(); if (!preg_match('/^content-length:\\s+(\\d+)/mi', $request, $match)) { $this->fail("Unable to find content-length header in request"); } $this->assertEquals(filesize($bodyFile), (int) $match[1]); }
protected function post($url, $data) { $request = new Request(); $request->setUri($url); $request->setMethod('POST'); $request->getPost()->fromArray($data); $client = new Client(); $client->setEncType(Client::ENC_URLENCODED); $response = $client->dispatch($request); try { $result = Json::decode($response->getBody(), Json::TYPE_ARRAY); return $result; } catch (RuntimeException $e) { return $response->getBody(); } }
/** * 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(); }
public function getOauthTokenFromAuthoriseGrant($params) { $client = new Client($params['sso_oauth_url'], array('maxredirects' => 0, 'timeout' => 30, 'sslcafile' => 'data/ca-bundle.pem')); $client->setMethod('POST'); $client->setEncType($params['encoding_type']); $params = array('redirect_uri' => $params['sso_redirect_uri'], 'client_id' => $params['sso_client_id'], 'client_secret' => $params['sso_secret'], 'code' => $params['code'], 'grant_type' => $params['grant_type'], 'response_type' => $params['response_type']); $client->setParameterPost($params); $response = $client->send(); if (!$response instanceof Response) { return false; } $data = json_decode($response->getBody()); if (!isset($data->access_token) or !isset($data->expires_in) or !isset($data->token_type) or !isset($data->scope) or !isset($data->refresh_token)) { return ['status' => false, 'message' => 'Invalid response']; } $date = new \DateTime(); $interval = $data->expires_in; $date->add(new \DateInterval('PT' . $interval . 'S')); return ['status' => true, 'token' => $data->access_token, 'type' => $data->token_type, 'expires' => $date, 'scope' => $data->scope, 'refresh_token' => $data->refresh_token]; }
/** * Add a new subscription * * @return JsonModel */ public function create($data) { $username = $this->params()->fromRoute('username'); $usersTable = $this->getTable('UsersTable'); $user = $usersTable->getByUsername($username); $userFeedsTable = $this->getTable('UserFeedsTable'); $rssLinkXpath = '//link[@type="application/rss+xml"]'; $faviconXpath = '//link[@rel="shortcut icon"]'; $client = new Client($data['url']); $client->setEncType(Client::ENC_URLENCODED); $client->setMethod(\Zend\Http\Request::METHOD_GET); $response = $client->send(); if ($response->isSuccess()) { $html = $response->getBody(); $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"); $dom = new Query($html); $rssUrl = $dom->execute($rssLinkXpath); if (!count($rssUrl)) { return new JsonModel(array('result' => false, 'message' => 'Rss link not found in the url provided')); } $rssUrl = $rssUrl->current()->getAttribute('href'); $faviconUrl = $dom->execute($faviconXpath); if (count($faviconUrl)) { $faviconUrl = $faviconUrl->current()->getAttribute('href'); } else { $faviconUrl = null; } } else { return new JsonModel(array('result' => false, 'message' => 'Website not found')); } $validator = new NoRecordExists(array('table' => 'user_feeds', 'field' => 'url', 'adapter' => $this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter'))); if (!$validator->isValid($rssUrl)) { return new JsonModel(array('result' => false, 'message' => 'You already have a subscription to this url')); } $rss = Reader::import($rssUrl); return new JsonModel(array('result' => $userFeedsTable->create($user->id, $rssUrl, $rss->getTitle(), $faviconUrl))); }
public function sendMessage($postdata) { $defaults = array('publisher' => $this->config['publisher'], 'provider' => '', 'message' => '', 'message_plain' => '', 'lang' => '', 'property_reference' => '', 'salutation_code' => '', 'firstname' => '', 'lastname' => '', 'legal_name' => '', 'street' => '', 'postal_code' => '', 'locality' => '', 'phone' => '', 'mobile' => '', 'fax' => '', 'email' => ''); $postdata = array_merge($defaults, $postdata); $postdata['publisher'] = $this->config['publisher']; if ($postdata['message'] && !$postdata['message_plain']) { $postdata['message'] = $this->sanitizeHtml($postdata['message']); $postdata['message_plain'] = strip_tags($postdata['message']); } if (!$postdata['message'] && $postdata['message_plain']) { $postdata['message_plain'] = strip_tags($postdata['message_plain']); $postdata['message'] = $this->sanitizeHtml($postdata['message_plain']); } if ($postdata['message'] && $postdata['message_plain']) { $postdata['message_plain'] = strip_tags($postdata['message_plain']); $postdata['message'] = $this->sanitizeHtml($postdata['message_plain']); } $config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FRESH_CONNECT => true)); $query = array(); $uri = $this->config['url'] . '/msg?' . http_build_query($query); $client = new HttpClient($uri, $config); $client->setHeaders(array('Accept' => 'application/json; charset=UTF-8', 'Content-Type' => 'application/json')); $client->setMethod('POST'); $client->setRawBody(Json::encode($postdata)); $client->setEncType(HttpClient::ENC_FORMDATA); $client->setAuth($this->config['username'], $this->config['password'], \Zend\Http\Client::AUTH_BASIC); $response = $client->send(); return $response->getContent(); }
/** * Sets a proper EncType on the given \Zend\Http\Client object (for UrlEncoded Request, used value is Client::ENC_URLENCODED) * * @param \Zend\Http\Client $client the Zend http client object * * @return mixed|\Zend\Http\Client */ public function setClientEncType(\Zend\Http\Client $client) { // Setting EncType to UrlEncoded $client->setEncType(\Zend\Http\Client::ENC_URLENCODED); return $client; }
public function logMsg($message, $priority = 7) { $config = array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_FRESH_CONNECT => true)); $query = array(); $uri = $this->config['url'] . '/msg?' . http_build_query($query); $client = new HttpClient($uri, $config); $client->setHeaders(array('Accept' => 'application/json; charset=UTF-8', 'Content-Type' => 'application/json')); $client->setMethod('POST'); $client->setRawBody(Json::encode(array('software' => $this->config['software'], 'message' => $message, 'priority' => $priority, 'priorityName' => array_search($priority, $this->priorities), 'timestamp' => date('Y-m-dTH:i:s', time())))); $client->setEncType(HttpClient::ENC_FORMDATA); $client->setAuth($this->config['username'], $this->config['password'], \Zend\Http\Client::AUTH_BASIC); try { $response = $client->send(); } catch (\Exception $e) { //probably timeout thats ok ^^; } return true; }
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); }
/** * Post a solution to the verify server * * @param string $challengeField * @param string $responseField * @return \Zend\Http\Response * @throws \ZendService\ReCaptcha\Exception */ protected function post($responseField) { if ($this->secretKey === null) { throw new Exception('Missing secret key'); } if (empty($responseField)) { throw new Exception('Missing response field'); } /* Fetch an instance of the http client */ $httpClient = new HttpClient(self::VERIFY_SERVER, array('adapter' => 'Zend\\Http\\Client\\Adapter\\Socket', 'sslcapath' => '/etc/ssl/certs')); $postParams = array('secret' => $this->secretKey, 'response' => $responseField); if ($this->ip !== null) { $postParams['remoteip'] = $this->ip; } $httpClient->setParameterPost($postParams); $httpClient->setMethod(HttpRequest::METHOD_POST); $httpClient->setEncType($httpClient::ENC_URLENCODED); return $httpClient->send(); }
/** * Handle the creation of a new link * * @param array $data * @return JsonModel */ protected function createLink($data) { $userLinksTable = $this->getUserLinksTable(); $filters = $userLinksTable->getInputFilter(); $filters->setData($data); if ($filters->isValid()) { $data = $filters->getValues(); $client = new Client($data['url']); $client->setEncType(Client::ENC_URLENCODED); $client->setMethod(\Zend\Http\Request::METHOD_GET); $response = $client->send(); if ($response->isSuccess()) { $html = $response->getBody(); $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"); $dom = new Query($html); $title = $dom->execute('title')->current()->nodeValue; if (!empty($title)) { $filterChain = new FilterChain(); $filterChain->attach(new StripTags()); $filterChain->attach(new StringTrim()); $filterChain->attach(new StripNewLines()); $title = $filterChain->filter($title); } else { $title = NULL; } return new JsonModel(array('result' => $userLinksTable->create($data['user_id'], $data['url'], $title))); } } return new JsonModel(array('result' => false, 'errors' => $filters->getMessages())); }