public function consultaTransacao($dadosCriptografados) { $xml = Request::get(static::URL_CONSULTA_TRANSACOES . $dadosCriptografados)->withoutStrictSsl()->expectsXml()->send(); if (!$xml) { throw new \Exception("Nenhum dado coletado no webservice"); } if ($xml->code != 200) { throw new \Exception("O servidor retornou status {$xml->code}"); } return $this->populateConsultaTransacao($xml->body); }
private function sendRequest($url, $data, array $options = null, $auth = null, $apiKey = null) { array_merge($this->_headers, $options); if ($this->_method == GET) { $url = $url . http_build_query($data); $this->_result = Request::get($url)->send(); } else { if ($this->_method == POST) { if (isset($apiKey)) { $url .= array_keys($apiKey)[0] . "=" . array_values($apiKey)[0]; } $request = Request::post($url); foreach ($this->_headers as $key => $hdr) { $request = $request->addHeader($key, $hdr); } if ($this->headers["Content-Type"] = "application/x-www-form-urlencoded" and is_array($data)) { $request = $request->body(http_build_query($data)); } else { $request = $request->body($data); } if (isset($auth)) { $request = $request->authenticateWith(array_keys($auth)[0], array_values($auth)[0]); } $this->_result = $request->send(); } } }
public function testCitiesListContainsAmsterdam() { $uri = "http://localhost:8000"; $response = Request::get($uri)->send(); $this->assertEquals("application/json", $response->headers["Content-Type"]); $this->assertContains("Amsterdam", $response->body); }
public function getRates(Currency $base) { $rates = (array) Request::get(sprintf('http://api.fixer.io/latest?base=%s', $base->getName()))->send()->body->rates; $ret = []; foreach ($rates as $key => $rate) { $ret[$key] = $rate; } return $ret; }
function getPhotos($category, $posts) { $is_highlights = !is_array($posts); $data = !$is_highlights ? $posts : []; $url = 'http://' . $_SERVER['SERVER_NAME'] . '/' . 'cms/wp-json/posts?filter[posts_per_page]=-1&filter[order]=desc&filter[orderby]=post_date' . ($is_highlights ? '&filter[category_name]=destaque' : null); $response = \Httpful\Request::get($url)->send(); $catId = get_cat_ID($category); foreach ($response->body as $key => $post) { $image_src = getImage($post->content); $attachment_id = pn_get_attachment_id_from_url($image_src); $image_large_src = wp_get_attachment_image_src($attachment_id, 'large'); if (!$is_highlights && !isHighgligthCategory($catId, $post->terms->category)) { if ($image_src) { array_push($data, array('id' => $post->ID, 'title' => $post->title, 'image_src' => getImage($post->content), 'image_large_src' => $image_large_src[0])); } } else { if ($is_highlights && isHighgligthCategory($catId, $post->terms->category)) { if ($image_src) { array_push($data, array('id' => $post->ID, 'title' => $post->title, 'image_src' => getImage($post->content), 'image_large_src' => $image_large_src[0])); } } } } return $data; }
protected function httpGet($uri) { $results = []; // Start requesting at page 1 $page = 1; // We dont know how many pages there are, so assume 1 until we know $pagecount = 1; while ($page <= $pagecount) { $this->log[] = ['request' => ['method' => 'GET', 'uri' => $uri . '?page=' . $page]]; $response = \Httpful\Request::get($uri . '?page=' . $page)->addHeader('X-Auth-Email', $this->email)->addHeader('X-Auth-Key', $this->apikey)->expectsType(\Httpful\Mime::JSON)->parseWith(function ($body) { return \Metaclassing\Utility::decodeJson($body); })->send()->body; $this->log[count($this->log) - 1]['response'] = $response; if ($response['success'] != true) { throw new \Exception("get {$uri} unsuccessful" . \Metaclassing\Utility::encodeJson($response)); } foreach ($response['result'] as $result) { array_push($results, $result); } // Now that we KNOW the pagecount, update that and increment our page counter $pagecount = $response['result_info']['total_pages']; // And get the next page ready for the next request $page++; } return $results; }
/** * {@inheritdoc} */ public function get($url) { $response = Request::get($url)->sendsJson()->addHeader("Accept", "application/json")->addHeader('X-TOKEN', $this->api)->send(); if ($this->isResponseOk($response->code)) { return $response->body; } }
public function fetchOriginal($showTitle, $season, $episode) { $episodeLink = $this->fetchEpisodeLink($showTitle, $season, $episode); $doc = Request::get($episodeLink)->send()->body; $dom = new DOMDocument('1.0', 'utf-8'); @$dom->loadHTML($doc); $xp = new DOMXPath($dom); $links = $xp->query('//strong[text()="original"]'); if ($links->length == 0) { $links = $xp->query('//table[@class="tabel95"]//td[@class="language"][contains(text(),"English")]'); if ($links->length == 0) { echo "Subtitle not found: {$episodeLink}\n"; return; } else { $tds = $links; $links = []; foreach ($tds as $td) { $linkNode = $xp->query('../td/a[@class="buttonDownload"]/strong', $td)->item(0); if ($linkNode) { $links[] = $linkNode; } } } } foreach ($links as $linkNode) { $link = $linkNode->parentNode->getAttribute('href'); $subLink = "http://www.addic7ed.com{$link}"; $response = Request::get($subLink)->addHeader('Referer', $episodeLink)->send(); $disp = $response->headers['Content-Disposition']; preg_match('/filename="([^"]+)"/', $disp, $m); return ['filename' => $m[1], 'body' => $response->body]; } }
/** * Send the HipChat message. * * @return void */ public function send() { $message = $this->message ?: ucwords($this->getSystemUser()) . ' ran the [' . $this->task . '] task.'; $format = $message != strip_tags($message) ? 'html' : 'text'; $payload = ['auth_token' => $this->token, 'room_id' => $this->room, 'from' => $this->from, 'message' => $message, 'message_format' => $format, 'notify' => 1, 'color' => $this->color]; Request::get('https://api.hipchat.com/v1/rooms/message?' . http_build_query($payload))->send(); }
private function fetch(&$str, $productid, $page, $count) { echo 'page is ' . $page . PHP_EOL; // echo 'current str length is '.strlen($str).PHP_EOL; $has_more = true; $url = sprintf($this->url_format, $productid, $page, $count); $headers = ['Cookie' => '_customId=q77dbffe7014; _snmc=1; _snsr=direct%7Cdirect%7C%7C%7C; _snma=1%7oC143589353017297011%7C1435893530172%7C1435893530172%7C1435893530171%7C1%7C1; _snmp=143589353016073744; _snmb=143589353017914712%7C1435893530308%7C1435893530180%7C1; _ga=GA1.2.833540218.1435893530; _snmz=143589353016073744%7C%281049%2C3268%29']; try { $response_ = Request::get($url)->addHeaders($headers)->autoParse(false)->send(); } catch (\Exception $e) { return false; } //生成一个csv文件格式 $json_str = substr($response_->raw_body, 11, -1); $arr = json_decode($json_str, true); // echo 'json_str is '.$json_str.PHP_EOL; // echo 'current json_str length is '.strlen($json_str).PHP_EOL; if (strlen($json_str) > 0 && !is_null($arr) && isset($arr['commodityReviews'])) { //echo "commodity reviews arr count is ".count($arr['commodityReviews']).PHP_EOL; foreach ($arr['commodityReviews'] as $comment) { $content = $comment['content']; str_replace('\'', '', $content); str_replace('"', '', $content); str_replace(',', '', $content); $str .= $content . "\r\n"; } } else { $has_more = false; } return $has_more; }
private function getResponse($url) { $response = \Httpful\Request::get($url)->send(); $responseraw = $response->raw_body; $result = json_decode($responseraw, true); return $result; }
function getNewsObjects() { //CACHING ENABLED: The server will only fetch news again if the cache has expired. Set expiry values in caching.php /*************** CACHE **************/ $newsCacheName = 'newscache'; $responsejson = null; $cacheExpired = is_null(checkCache($newsCacheName)); $noCache = !is_null($_GET["nocache"]); //////////////////////// if ($cacheExpired || $noCache) { $uri = "http://api.nytimes.com/svc/news/v3/content/all/all.json?api-key={$newsapikey}"; $rawresponsejson = \Httpful\Request::get($uri)->send(); $responsejson = $rawresponsejson . raw_body; setCacheVal($newsCacheName, $responsejson); if ($debug) { echo "Fetched."; } } else { if ($debug) { echo "From cache."; } $responsejson = getCacheVal($newsCacheName); } return parseArticleObjectsFromJson($responsejson); }
public function authenticate($ticket, $service) { $r = Request::get($this->getValidateUrl($ticket, $service))->sendsXml()->timeoutIn($this->timeout)->send(); $r->body = str_replace("\n", "", $r->body); try { $xml = new SimpleXMLElement($r->body); } catch (\Exception $e) { throw new \UnexpectedValueException("Return cannot be parsed : '{$r->body}'"); } $namespaces = $xml->getNamespaces(); $serviceResponse = $xml->children($namespaces['cas']); $user = $serviceResponse->authenticationSuccess->user; if ($user) { return (string) $user; // cast simplexmlelement to string } else { $authFailed = $serviceResponse->authenticationFailure; if ($authFailed) { $attributes = $authFailed->attributes(); throw new \Exception((string) $attributes['code']); } else { throw new \Exception($r->body . " service:" . $service); } } // never reach there }
/** * Reset passbolt installation * @return bool */ public static function resetDatabase($url, $dummy = 'seleniumtests') { $response = \Httpful\Request::get($url . '/seleniumTests/resetInstance/' . $dummy)->send(); $seeCreated = preg_match('/created/', $response->body); sleep(2); // Wait for database to be imported (no visible output). return $seeCreated; }
/** * Returns the query in the response format requested. * (Ex: json, xml) * * @return mixed * Query response */ public function query() { // echo "\n YOUR QUERY \n" . $this->__toString() . "\n END QUERY \n"; $request = Request::get($this->__toString())->send(); $response = $request->raw_body; var_dump($request); return $response; }
/** * Calls API and returns its response (or null if code != 200) * @param $uri * @return array|null|object|string */ private function doRequest($uri) { $response = \Httpful\Request::get($uri)->authenticateWith($this->apiLogin, $this->apiPassword)->expects('json')->send(); if ($response->code != Response::HTTP_OK) { return null; } return $response->body; }
public function callApi($requestUrl) { $requestUrl = $this->baseUrl . $this->lang . $this->apiUrl . $requestUrl; $response = \Httpful\Request::get($requestUrl)->expectsJson()->send(); $transform = json_encode($response->body); $content = json_decode($transform, true); return $content; }
protected function get($uri, array $params = null) { if (!is_null($params)) { $params = self::clean_array($params); return self::process_response(Request::get(self::$base_uri . $uri . '?' . http_build_query($params))->send()); } return self::process_response(Request::get(self::$base_uri . $uri)->send()); }
function get($url, $destinationFile = false) { $response = \Httpful\Request::get($url)->send(); if (!$destinationFile) { return $response; } else { file_put_contents($destinationFile, $response); } }
/** * 获取一个学生的基本信息 * * @param $token * @return array|null */ public function getStudentInfo($token) { $response = \Httpful\Request::get($this->ssoAPIHost . '/info/student?sessionid=' . urlencode($token))->expectsJson()->send(); // 包含 msg,则代表失败 if (!$response->body->ok) { return null; } return (array) $response->body->info; }
/** * @param string $url * @param array $headers * @return mixed */ public function get($url = '', $headers = array()) { // Set headers $this->setHeaders($headers); // Set template $this->setTemplate('get'); // Perform the request $this->data = Request::get($url)->send(); }
/** * Send Request to API-Server * @return self */ public function send() { if (is_null($this->what) && is_null($this->where)) { throw new Exception("No Searchparameter given"); } $uri = $this->getUri(); $response = Request::get($uri)->expectsXml()->send(); return new Response($response); }
public function findMany(array $ids) { $array = array(); foreach ($ids as $id) { $uri = $this->BASE_URL . "citizen/profile/" . $id . "." . $this->TYPE; $response = Request::get($uri)->send(); $array[$id] = json_decode($response); } return $array; }
public function findMany(array $ids) { $array = array(); foreach ($ids as $regiment => $unit) { $uri = $this->BASE_URL . "unit/" . $unit . "/" . $regiment . "." . $this->TYPE; $response = Request::get($uri)->send(); $array[$regiment] = json_decode($response); } return $array; }
public function logout() { $r = \Httpful\Request::get($this->url . "logout")->sendsXml()->timeoutIn($this->timeout)->send(); $r->body = str_replace("\n", "", $r->body); try { $xml = new SimpleXMLElement($r->body); return true; } catch (\Exception $e) { return false; } }
/** * Checks to see if a video is unavailable on YouTube * @param string $link_url The URL to the video or video resource * @return bool TRUE if a video is unavailable for any reason (Copyright, Deleted, Private, etc.), FALSE if the video exists */ function videoUnavailable($link_url) { $url = 'https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id='; $api_key = constant('GOOGLE_API_KEY'); if ($youtube_id = $this->isYouTubeVideo($link_url)) { $url = $url . $youtube_id . '&key=' . $api_key; $response = Request::get($url)->send(); return empty($response->body->items) ? true : false; } return false; }
public static function get($url, $data = [], $auth = false) { $api = self::$api; $response = \Httpful\Request::get($api['url'] . $url); // Will parse based on Content-Type if ($auth) { $response->authenticateWith($api['username'], $api['password']); } $response = $response->sendsJson()->body(json_encode($data))->send(); return (array) $response->body; }
public function get($url) { $verb = 'GET'; $request = \Httpful\Request::get($this->endpointUrl . $url)->expectsJson()->addHeader('Authorization', 'Bearer ' . $this->accessToken); try { $httpResponse = $request->send(); } catch (\Httpful\Exception\ConnectionErrorException $ex) { throw new RestUnreachableException($verb, $url, $ex); } $this->checkResponse($verb, $url, $httpResponse); return $httpResponse->body; }
public function dequeueExperiment() { try { $response = Request::get($this->base_url . '/experiment')->authenticateWith($this->username, $this->password)->addHeader('X-apikey', $this->apikey)->send(); } catch (Exception $e) { return array('is_Exception' => true, 'error_message' => $e->getMessage()); } if ($response->code != 200) { return array('is_exception' => true, 'error_message' => "Request failed with HTTP Error " . $response->code); } return array('is_exception' => false, 'result' => (array) json_decode($response->body)); }
/** * @param Request $request * * @return HttpServer */ public function getHttpServer(Request $request) { $url = $request->getUri(); switch ($request->getMethod()) { case Request::METHOD_POST: $httpServer = HttpServer::post($url); break; case Request::METHOD_PUT: $httpServer = HttpServer::put($url); break; case Request::METHOD_DELETE: $httpServer = HttpServer::delete($url); break; default: $httpServer = HttpServer::get($url); break; } if ($request->headers) { $httpServer->addHeaders($request->headers->all()); } if ($request->getUser()) { $httpServer->authenticateWith($request->getUser(), $request->getPassword()); } if ($request->getContent()) { $httpServer->body($request->getContent()); } return $httpServer; }