/** * Performs the test. * * @return \Jyxo\Beholder\Result */ public function run() { // The http extension is required if (!extension_loaded('http')) { return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::NOT_APPLICABLE, 'Extension http missing'); } $http = new \HttpRequest($this->url, \HttpRequest::METH_GET, array('connecttimeout' => 5, 'timeout' => 10, 'useragent' => 'JyxoBeholder')); try { $http->send(); if (200 !== $http->getResponseCode()) { throw new \Exception(sprintf('Http error: %s', $http->getResponseCode())); } if (isset($this->tests['body'])) { $body = $http->getResponseBody(); if (!preg_match($this->tests['body'], $body)) { $body = trim(strip_tags($body)); throw new \Exception(sprintf('Invalid body: %s', \Jyxo\String::cut($body, 16))); } } // OK return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::SUCCESS); } catch (\HttpException $e) { $inner = $e; while (null !== $inner->innerException) { $inner = $inner->innerException; } return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, $inner->getMessage()); } catch (\Exception $e) { return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, $e->getMessage()); } }
/** * Copyright (C) 2008-2010 Ulteo SAS * http://www.ulteo.com * Author Julien LANGLOIS <*****@*****.**> * Author Laurent CLOUET <*****@*****.**> * Author Jeremy DESVAGES <*****@*****.**> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ function query_url_request($url_, $log_returned_data_ = true, $data_in_file_ = false) { Logger::debug('main', "query_url_request({$url_},{$log_returned_data_}, {$data_in_file_})"); $hr = new HttpRequest($url_, 'GET'); if ($data_in_file_ === true) { $data_file = tempnam(NULL, 'curl_'); $fp = fopen($data_file, 'w'); $hr->setToFile($fp); } $data = $hr->send(); if ($data_in_file_ === true) { $data = $data_file; fclose($fp); } if ($data === false) { Logger::error('main', "query_url_request({$url_}) error code: " . $hr->getResponseErrno() . " text: '" . $hr->getResponseError() . "'"); } else { if (str_startswith($hr->getResponseContentType(), 'text/') && $log_returned_data_ === true) { Logger::debug('main', "query_url_request({$url_}) returntext: '{$data}'"); } } if ($hr->getResponseCode() != 200) { Logger::debug('main', "query_url_request({$url_}) returncode: '" . $hr->getResponseCode() . "'"); } return array('data' => $data, 'code' => $hr->getResponseCode(), 'content_type' => $hr->getResponseContentType()); }
public function OnStartForking() { $db = \Scalr::getDb(); // Get pid of running daemon $pid = @file_get_contents(CACHEPATH . "/" . __CLASS__ . ".Daemon.pid"); $this->Logger->info("Current daemon process PID: {$pid}"); // Check is daemon already running or not if ($pid) { $Shell = new Scalr_System_Shell(); // Set terminal width putenv("COLUMNS=400"); // Execute command $ps = $Shell->queryRaw("ps ax -o pid,ppid,command | grep ' 1' | grep {$pid} | grep -v 'ps x' | grep DBQueueEvent"); $this->Logger->info("Shell->queryRaw(): {$ps}"); if ($ps) { // daemon already running $this->Logger->info("Daemon running. All ok!"); return true; } } $rows = $db->Execute("SELECT history_id FROM webhook_history WHERE status='0'"); while ($row = $rows->FetchRow()) { $history = WebhookHistory::findPk(bin2hex($row['history_id'])); if (!$history) { continue; } $endpoint = WebhookEndpoint::findPk($history->endpointId); $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); if ($endpoint->url == 'SCALR_MAIL_SERVICE') { $request->setUrl('https://my.scalr.com/webhook_mail.php'); } else { $request->setUrl($endpoint->url); } $request->setOptions(array('timeout' => 3, 'connecttimeout' => 3)); $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D, d M Y H:i:s e"); $canonical_string = $history->payload . $timestamp; $signature = hash_hmac('SHA1', $canonical_string, $endpoint->securityKey); $request->addHeaders(array('Date' => $timestamp, 'X-Signature' => $signature, 'X-Scalr-Webhook-Id' => $history->historyId, 'Content-type' => 'application/json')); $request->setBody($history->payload); try { $request->send(); $history->responseCode = $request->getResponseCode(); if ($request->getResponseCode() <= 205) { $history->status = WebhookHistory::STATUS_COMPLETE; } else { $history->status = WebhookHistory::STATUS_FAILED; } } catch (Exception $e) { $history->status = WebhookHistory::STATUS_FAILED; } $history->save(); } }
/** * Send the request * * This function sends the actual request to the * remote/local webserver using pecl http * * @link http://us2.php.net/manual/en/http.request.options.php * @todo catch exceptions from HttpRequest and rethrow * @todo handle Puts */ public function sendRequest() { $options = array('connecttimeout' => $this->requestTimeout); // if we have any listeners register an onprogress callback if (count($this->_listeners) > 0) { $options['onprogress'] = array($this, '_onprogress'); } $tmp = 'HTTP_METH_' . strtoupper($this->verb); if (defined($tmp)) { $method = constant($tmp); } else { $method = HTTP_METH_GET; } $this->request = $request = new \HttpRequest($this->uri->url, $method, $options); $request->setHeaders($this->headers); if ($this->body) { $request->setRawPostData($this->body); } $request->send(); $response = $request->getResponseMessage(); $body = $response->getBody(); $details = $this->uri->toArray(); $details['code'] = $request->getResponseCode(); $details['httpVersion'] = $response->getHttpVersion(); $headers = new Request\Headers($response->getHeaders()); $cookies = $request->getResponseCookies(); return new Request\Response($details, $body, $headers, $cookies); }
public function testDeleteAsset() { $assetID = file_get_contents('test.assetid'); $r = new HttpRequest($this->server_url . $assetID, HttpRequest::METH_DELETE); $r->send(); $this->assertEquals(200, $r->getResponseCode()); }
protected function request($path, $args = array(), $files = array(), $envId = 0, $version = 'v1') { try { $httpRequest = new HttpRequest(); $httpRequest->setMethod(HTTP_METH_POST); $postData = json_encode($args); $stringToSign = "/{$version}{$path}:" . $this->API_ACCESS_KEY . ":{$envId}:{$postData}:" . $this->API_SECRET_KEY; $validToken = Scalr_Util_CryptoTool::hash($stringToSign); $httpRequest->setHeaders(array("X_SCALR_AUTH_KEY" => $this->API_ACCESS_KEY, "X_SCALR_AUTH_TOKEN" => $validToken, "X_SCALR_ENV_ID" => $envId)); $httpRequest->setUrl("http://scalr-trunk.localhost/{$version}{$path}"); $httpRequest->setPostFields(array('rawPostData' => $postData)); foreach ($files as $name => $file) { $httpRequest->addPostFile($name, $file); } $httpRequest->send(); if ($this->debug) { print "<pre>"; var_dump($httpRequest->getRequestMessage()); var_dump($httpRequest->getResponseCode()); var_dump($httpRequest->getResponseData()); } $data = $httpRequest->getResponseData(); return @json_decode($data['body']); } catch (Exception $e) { echo "<pre>"; if ($this->debug) { var_dump($e); } else { var_dump($e->getMessage()); } } }
protected function request($method, $uri, $args) { $parsedUrl = parse_url($this->ec2Url); $uri = "{$parsedUrl['path']}{$uri}"; $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)")); $args['Version'] = $this->apiVersion; $args['SignatureVersion'] = 2; $args['SignatureMethod'] = "HmacSHA256"; $args['Timestamp'] = $this->getTimestamp(); $args['AWSAccessKeyId'] = $this->accessKeyId; ksort($args); foreach ($args as $k => $v) { $CanonicalizedQueryString .= "&{$k}=" . rawurlencode($v); } $CanonicalizedQueryString = trim($CanonicalizedQueryString, "&"); $url = $parsedUrl['port'] ? "{$parsedUrl['host']}:{$parsedUrl['port']}" : "{$parsedUrl['host']}"; $args['Signature'] = $this->getSignature(array($method, $url, $uri, $CanonicalizedQueryString)); $HttpRequest->setUrl("{$parsedUrl['scheme']}://{$url}{$uri}"); $HttpRequest->setMethod(constant("HTTP_METH_{$method}")); if ($args) { if ($method == 'POST') { $HttpRequest->setPostFields($args); $HttpRequest->setHeaders(array('Content-Type' => 'application/x-www-form-urlencoded')); } else { $HttpRequest->addQueryData($args); } } try { $HttpRequest->send(); $data = $HttpRequest->getResponseData(); if ($HttpRequest->getResponseCode() == 200) { $response = simplexml_load_string($data['body']); if ($this->responseFormat == 'Object') { $json = @json_encode($response); $response = @json_decode($json); } if ($response->Errors) { throw new Exception($response->Errors->Error->Message); } else { return $response; } } else { $response = @simplexml_load_string($data['body']); if ($response) { throw new Exception($response->Error->Message); } throw new Exception(trim($data['body'])); } $this->LastResponseHeaders = $data['headers']; } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception($message); } }
/** * Query past cashpot draws by date. * @param day a two digit representation of the day eg. 09 * @param month a three letter representation of the month eg. Jan * @param year a two digit representation of the year eg. 99 * @return the raw html from the page returned by querying a past cashpot draw. */ function query_draw_history($day, $month, $year) { $url = "http://www.nlcb.co.tt/search/cpq/cashQuery.php"; $fields = array('day' => $day, 'month' => $month, 'year' => $year); $request = new HttpRequest($url, HttpRequest::METH_POST); $request->addPostFields($fields); try { $request->send(); if ($request->getResponseCode() == 200) { $response = $request->getResponseBody(); } else { throw new Exception("Request for {$url} was unsuccessful. A " . $request->getResponseCode() . " response code was returned."); } } catch (HttpException $e) { echo $e->getMessage(); throw $e; } return $response; }
public function test() { $route = 'http://localhost/wordpress/augsburg/de/wp-json/extensions/v0/ modified_content/posts_and_pages'; $r = new HttpRequest($route, HttpRequest::METH_GET); $r->addQueryData(array('since' => '2000-01-01T00:00:00Z')); $r->send(); $this->assertEquals(200, $r->getResponseCode()); $body = $r->getResponseBody(); }
protected function request($uri, $method, $data) { $httpRequest = new HttpRequest(); $httpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)")); $httpRequest->setUrl("{$this->apiUrl}{$uri}"); $httpRequest->setMethod($method); $httpRequest->resetCookies(); $httpRequest->addHeaders(array('Cookie' => $this->sessionCookie, 'Content-Type' => 'application/nimbula-v1+json')); switch ($method) { case HTTP_METH_POST: $httpRequest->setRawPostData(json_encode($data)); $httpRequest->addHeaders(array('Content-Type' => 'application/nimbula-v1+json')); break; } try { $httpRequest->send(); $data = $httpRequest->getResponseData(); $result = @json_decode($data['body']); if ($httpRequest->getResponseCode() > 204) { $message = $result->message; if ($message) { if ($message instanceof stdClass) { $r = (array) $message; $msg = ''; foreach ($r as $k => $v) { $msg .= "{$k}: {$v} "; } throw new Exception(trim($msg)); } else { throw new Exception($message); } } throw new Exception($data['body']); } $headers = $httpRequest->getResponseHeader('Set-Cookie'); if ($headers) { if (!is_array($headers)) { if (stristr($headers, "nimbula")) { $this->sessionCookie = $headers; } } else { } } $this->LastResponseHeaders = $data['headers']; return $result; } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception("Nimbula error: {$message}"); } }
function http_get_file($url) { $r = new HttpRequest($url, HttpRequest::METH_GET); $r->setOptions(array('redirect' => 5)); try { $r->send(); if ($r->getResponseCode() == 200) { $dir = $r->getResponseBody(); } else { echo "Respose code " . $r->getResponseCode() . "({$url})\n"; echo $r->getResponseBody() . "({$url})\n"; return "-2"; } } catch (HttpException $ex) { echo $ex; return "-3"; } $dir = strip_tags($dir); return explode("\n", $dir); // An array of lines from the url }
/** * Permet d'avoir la liste de toutes les comp�titions. * (Seul la Premier League est disponible avec un forfait gratuit) * @return mixed */ public static function getCompetitionsPremierLeague() { $reqCometition = 'http://football-api.com/api/?Action=competitions&APIKey=' . self::API_KEY; $reponse = new HttpRequest($reqCometition, HttpRequest::METH_GET); try { $reponse->send(); if ($reponse->getResponseCode() == 200) { return json_decode($reponse->getResponseBody()); } } catch (HttpException $ex) { echo $ex; } }
private function request($method, Object $params = null) { $requestObj = new stdClass(); $requestObj->id = microtime(true); $requestObj->method = $method; $requestObj->params = $params; $jsonRequest = json_encode($requestObj); $timestamp = date("D d M Y H:i:s T"); $dt = new DateTime($timestamp, new DateTimeZone("CDT")); $timestamp = Scalr_Util_DateTime::convertDateTime($dt, new DateTimeZone("UTC"), new DateTimeZone("CDT"))->format("D d M Y H:i:s"); $timestamp .= " UTC"; $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 1)); $request = new HttpRequest("http://{$this->dbServer->remoteIp}:{$this->port}/", HTTP_METH_POST); $request->setOptions(array('timeout' => 5, 'connecttimeout' => 5)); $request->setHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId)); $request->setRawPostData($jsonRequest); try { // Send request $request->send(); if ($request->getResponseCode() == 200) { $response = $request->getResponseData(); $jResponse = @json_decode($response['body']); if ($jResponse->error) { throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data}"); } return $jResponse; } else { throw new Exception(sprintf("Unable to perform request to update client: %s", $request->getResponseCode())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } throw new Exception(sprintf("Unable to perform request to update client: %s", $msg)); } }
private static function fetchData($station, $time, $lang, $timeSel) { //temporal public credentials for the NS API. $url = "http://" . urlencode("*****@*****.**") . ":" . urlencode("fEoQropezniTJRw_5oKhGVlFwm_YWdOgozdMjSAVPLk3M3yZYKEa0A") . "@webservices.ns.nl/ns-api-avt?station=" . $station->name; $r = new HttpRequest($url, HttpRequest::METH_GET); try { $r->send(); if ($r->getResponseCode() == 200) { return new SimpleXMLElement($r->getResponseBody()); } } catch (HttpException $ex) { throw new Exception("Could not reach NS server", 500); } }
/** * Static constructor * * @param string $url * @param string $tmp * @return BigGet * @throws Exception */ public static function url($url, $tmp = '/tmp') { $head = new HttpRequest($url, HttpRequest::METH_HEAD); $headers = $head->send()->getHeaders(); if (200 != $head->getResponseCode()) { throw new HttpException("Did not receive '200 Ok' from HEAD {$url}"); } if (!isset($headers['Accept-Ranges'])) { throw new HttpException("Did not receive an Accept-Ranges header from HEAD {$url}"); } if (!isset($headers['Content-Length'])) { throw new HttpException("Did not receive a Content-Length header from HEAD {$url}"); } $bigget = new BigGet(); $bigget->url = $url; $bigget->tmp = tempnam($tmp, 'BigGet.'); $bigget->size = $headers['Content-Length']; return $bigget; }
public function Login() { $signature = $this->SignMessage("frob", $this->Frob, "perms", "delete"); $query = "api_key={$this->ApiKey}&perms=delete&frob={$this->Frob}&api_sig={$signature}"; $request = new HttpRequest("http://flickr.com/services/auth/", HTTP_METH_GET); $request->setQueryData($query); $request->enableCookies(); $request->setOptions(array( "redirect" => 10, "useragent" => "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" ) ); $request->send(); var_dump($request->getResponseCode()); print_r($request->getResponseBody()); var_dump($request->getResponseStatus()); }
<?php require_once __DIR__ . '/ispy_config.php'; date_default_timezone_set('America/Los_Angeles'); $ispy_config = new IspyConfig(); // make GET request to pick up latest instagram photos $r = new HttpRequest('https://api.instagram.com/v1/tags/foolprooffour/media/recent?client_id=' . $ispy_config->instagram_client_id, HttpRequest::METH_GET); try { $r->send(); if ($r->getResponseCode() == 200) { $results = $r->getResponseBody(); $results = json_decode($results, true); } } catch (HttpException $ex) { echo $ex; } /** * adding instagram photos to the db */ $sqli = new Sqlite3($ispy_config->db); if (!$sqli) { die('Could not connect: ' . $sqli->lastErrorMsg); } // pull latest photo from db and it's created time $sql = "SELECT `date_added` FROM `uploads` ORDER BY `id` DESC LIMIT 1;"; $sqli_result = $sqli->query($sql); $latest_date_str = $sqli_result->fetchArray(SQLITE3_ASSOC); $latest_date = strtotime($latest_date_str["date_added"]); if (!$sqli_result) { die('ispy insert not completed: ' . $sqli->lastErrorMsg); }
public function request($method, stdClass $params = null, $namespace = null) { if (!$namespace) { $namespace = $this->namespace; } $requestObj = new stdClass(); $requestObj->id = microtime(true); $requestObj->method = $method; $requestObj->params = new stdClass(); $this->walkSerialize($params, $requestObj->params, 'underScope'); $jsonRequest = $this->cryptoTool->encrypt(json_encode($requestObj), $this->dbServer->GetKey(true)); $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D d M Y H:i:s e"); $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetKey(true), 1)); $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); // If no VPC router communicating via local inteface (Scalr should be setup within the esame network) $requestHost = $this->dbServer->getSzrHost() . ":{$this->port}"; if ($this->isVPC) { $routerFarmRoleId = $this->dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->dbServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->dbServer->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->dbServer->localIp, "X-Receiver-Port" => $this->port)); // There is public IP, can use it } else { $requestHost = "{$this->dbServer->remoteIp}:{$this->port}"; } } } $request->setUrl("http://{$requestHost}/{$namespace}"); $request->setOptions(array('timeout' => $this->timeout, 'connecttimeout' => 10)); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId)); $request->setBody($jsonRequest); try { // Send request $request->send(); $this->debug['responseCode'] = $request->getResponseCode(); $this->debug['fullResponse'] = $request->getRawResponseMessage(); if ($request->getResponseCode() == 200) { $response = $request->getResponseData(); $body = $this->cryptoTool->decrypt($response['body'], $this->dbServer->GetKey(true)); $jResponse = @json_decode($body); if ($jResponse->error) { throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data}"); } return $jResponse; } else { $response = $request->getResponseData(); throw new Exception(sprintf("Unable to perform request to scalarizr: %s (%s)", $response['body'], $request->getResponseCode())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } if (stristr($msg, "Namespace not found")) { $msg = "Feature not supported by installed version of scalarizr. Please update it to the latest version and try again."; } throw new Exception(sprintf("Unable to perform request to scalarizr: %s", $msg)); } }
private function request($method, $params = null) { $requestObj = new stdClass(); $requestObj->id = microtime(true); $requestObj->method = $method; $requestObj->params = $params; $jsonRequest = json_encode($requestObj); $newEncryptionProtocol = false; //TODO: if ($this->dbServer->farmRoleId) { if ($this->dbServer->IsSupported('2.7.7')) { $newEncryptionProtocol = true; } } $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D d M Y H:i:s e"); if ($newEncryptionProtocol) { $jsonRequest = $this->cryptoTool->encrypt($jsonRequest, $this->dbServer->GetKey(true)); $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetKey(true), 1)); } else { $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 1)); } $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); $requestHost = $this->dbServer->getSzrHost() . ":{$this->port}"; if ($this->isVPC) { $routerFarmRoleId = $this->dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->dbServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->dbServer->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->dbServer->localIp, "X-Receiver-Port" => $this->port)); // There is public IP, can use it } else { $requestHost = "{$this->dbServer->remoteIp}:{$this->port}"; } } } $request->setUrl($requestHost); $request->setOptions(array('timeout' => $this->timeout, 'connecttimeout' => $this->timeout)); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId)); $request->setBody($jsonRequest); try { // Send request $request->send(); if ($request->getResponseCode() == 200) { $response = $request->getResponseData(); $body = $response['body']; if ($newEncryptionProtocol) { $body = $this->cryptoTool->decrypt($body, $this->dbServer->GetKey(true)); } $jResponse = @json_decode($body); if ($jResponse->error) { throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data} ({$response['body']})"); } return $jResponse; } else { throw new Exception(sprintf("Unable to perform request to update client: %s", $request->getResponseCode())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } throw new Exception(sprintf("Unable to perform request to update client: %s", $msg)); } }
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetWeather xmlns="http://www.webserviceX.NET"> <CityName>singapore</CityName> <CountryName>singapore</CountryName> </GetWeather> </soap:Body> </soap:Envelope>'; $r->setBody($xmlSoapMessage); try { $r->send(); echo '<h2>Request Header</h2>'; echo '<pre>'; print_r($r->getRawRequestMessage()); echo '</pre>'; $responseCode = $r->getResponseCode(); $responseHeader = $r->getResponseHeader(); $responseBody = $r->getResponseBody(); echo '--------------------------------------------------------------------------------------------<br/>'; echo '<h2>Rseponse Code</h2>'; echo "resonse code " . $responseCode . "<br/>"; // echo "resonse header" . $responseHeader["location"] . "<br/>"; echo '<h2>Rseponse Header</h2>'; echo '<pre>'; print_r($responseHeader); echo '</pre>'; echo '<h2>Rseponse Body</h2>'; echo '<pre>'; print_r($responseBody); echo '</pre>'; } catch (HttpException $ex) {
/** * Send message to instance * @param Scalr_Messaging_Msg $message * @return Scalr_Messaging_Msg */ public function SendMessage(Scalr_Messaging_Msg $message, $isEventNotice = false, $delayed = false) { $startTime = microtime(true); if ($this->farmId && $message->getName() != 'BeforeHostTerminate') { if ($this->GetFarmObject()->Status == FARM_STATUS::TERMINATED) { $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::FAILED, $message->messageId)); return; } } // // To avoid message flood if server cannot respond // Protection from DDOS // Log only right now /* $pendingMessagesCount = $this->Db->GetOne("SELECT COUNT(*) FROM messages WHERE status = '0' OR server_id = ?", array( $this->serverId )); if ($pendingMessagesCount > 50) { if ($message->serverId != $this->serverId) { $this->SetProperty('tmp.flood-alert', 1); } } */ // Ignore OLD messages (ami-scripts) if (!$this->IsSupported("0.5")) { return; } // Put access data and reserialize message $pl = PlatformFactory::NewPlatform($this->platform); $pl->PutAccessData($this, $message); $logger = Logger::getLogger('DBServer'); $serializer = Scalr_Messaging_XmlSerializer::getInstance(); $cryptoTool = \Scalr::getContainer()->srzcrypto($this->GetKey(true)); if ($this->GetProperty(\SERVER_PROPERTIES::SZR_MESSAGE_FORMAT) == 'json') { $serializer = Scalr_Messaging_JsonSerializer::getInstance(); $rawMessage = $serializer->serialize($message); $messageType = 'json'; } else { $rawMessage = $serializer->serialize($message); $messageType = 'xml'; } //$rawJsonMessage = @json_encode($message); $time = microtime(true) - $startTime; if (!$this->Db->GetOne("SELECT COUNT(*) FROM `messages` WHERE `messageid` = ? AND `server_id` = ?", [$message->messageId, $this->serverId])) { // Add message to database $this->Db->Execute("INSERT INTO messages SET\n `messageid` = ?,\n `processing_time` = ?,\n `server_id` = ?,\n `event_server_id` = ?,\n `message` = ?,\n `type` = 'out',\n `message_name` = ?,\n `handle_attempts` = ?,\n `message_version` = ?,\n `dtlasthandleattempt` = NOW(),\n `dtadded` = NOW(),\n `message_format` = ?,\n `event_id` = ?\n ON DUPLICATE KEY UPDATE handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW()\n ", array($message->messageId, $time, $this->serverId, $message->serverId, $rawMessage, $message->getName(), $delayed ? '0' : '1', 2, $messageType, isset($message->eventId) ? $message->eventId : '')); } else { $this->Db->Execute("UPDATE messages SET handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW() WHERE messageid = ? AND server_id = ?", array($message->messageId, $this->serverId)); } if ($delayed) { return $message; } $isVPC = false; if ($this->farmId) { if (DBFarm::LoadByID($this->farmId)->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) { $isVPC = true; } } if (!$this->remoteIp && !$this->localIp && !$isVPC) { return; } $cryptoTool->setCryptoKey($this->GetKey(true)); $encMessage = $cryptoTool->encrypt($rawMessage); $timestamp = date("c", time()); $signature = $cryptoTool->sign($encMessage, null, $timestamp); try { $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); $ctrlPort = $this->getPort(self::PORT_CTRL); $requestHost = $this->getSzrHost() . ":{$ctrlPort}"; if ($isVPC) { $routerFarmRoleId = $this->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->localIp, "X-Receiver-Port" => $ctrlPort)); // There is public IP, can use it } else { $requestHost = "{$this->remoteIp}:{$ctrlPort}"; } } } //Prepare request $request->setUrl("http://{$requestHost}/control"); $request->setOptions(array('timeout' => \Scalr::config('scalr.system.instances_connection_timeout'), 'connecttimeout' => \Scalr::config('scalr.system.instances_connection_timeout'))); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, 'X-Server-Id' => $this->serverId)); if ($messageType == 'json') { $request->addHeaders(array('Content-type' => 'application/json')); } $request->setBody($encMessage); // Send request $request->send(); // Process response if ($request->getResponseCode() == 201) { $logger->info(sprintf("[FarmID: %s] Sending message '%s' via REST to server '%s' (server_id: %s) completed", $this->farmId, $message->getName(), $this->remoteIp, $this->serverId)); if (in_array($message->getName(), array('ExecScript'))) { $this->Db->Execute("DELETE FROM messages WHERE messageid = ?", array($message->messageId)); } else { if ($messageType != 'json') { $this->Db->Execute("UPDATE messages SET status = ?, message = '' WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId)); } else { $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId)); } if (!empty($message->eventId)) { $this->Db->Execute("UPDATE events SET msg_sent = msg_sent + 1 WHERE event_id = ?", array($message->eventId)); } } } else { $logger->warn(sprintf("[FarmID: %s] Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $this->farmId, $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $request->getResponseStatus())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } if ($this->farmId) { $logger->warn(new FarmLogMessage($this->farmId, sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg), $this->serverId)); } else { $logger->fatal(sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg)); } return false; } return $message; }
<?php error_reporting(E_ALL); while (1) { exec('iostat', $out); $data = array('data' => json_encode($out)); $data = http_build_query($data); try { //$req = new HttpRequest('http://172.16.100.114:3333/receive_http.php', HTTP_METH_POST); $req = new HttpRequest('http://172.16.100.114:3000', HTTP_METH_POST); $req->setBody($data); $req->send(); } catch (Exception $e) { echo 'ERR: ', $e->getMessage(), "\n"; exit(1); } if (200 === $req->getResponseCode()) { $body = $req->getResponseBody(); print_r(json_decode($body, true)); } else { $body = 'error'; } unset($out); echo date('r') . "\n"; sleep(1); }
private function request($path, $method, $data = "") { $data = trim($data); $httpRequest = new HttpRequest(); $httpRequest->setOptions(array("useragent" => "Scalr (http://scalr.com)")); $fullUrl = "{$this->chefServerUrl}{$path}"; $chunks = parse_url($fullUrl); if ($method == 'POST' && $data) { if (is_array($data)) { $httpRequest->setPostFields($data); } else { $httpRequest->setBody($data); } } if ($method == 'PUT' && $data) { $httpRequest->setPutData($data); } $httpRequest->setUrl($fullUrl); $httpRequest->setMethod(constant("HTTP_METH_{$method}")); $tz = @date_default_timezone_get(); date_default_timezone_set("UTC"); $timestamp = date("Y-m-d\\TH:i:s\\Z"); date_default_timezone_set($tz); $chunks['path'] = str_replace('//', '/', $chunks['path']); $hashedPath = base64_encode(sha1($chunks['path'], true)); $hashedBody = base64_encode(sha1($data, true)); $userId = $this->username; $str = "Method:{$method}\n" . "Hashed Path:{$hashedPath}\n" . "X-Ops-Content-Hash:{$hashedBody}\n" . "X-Ops-Timestamp:{$timestamp}\n" . "X-Ops-UserId:{$userId}"; $headers = array('x-ops-sign' => "algorithm=sha1;version=1.0", 'x-chef-version' => "0.10.8", 'x-ops-userid' => $userId, 'x-ops-timestamp' => $timestamp, 'x-ops-content-hash' => $hashedBody, 'content-type' => 'application/json', 'accept' => 'application/json'); $r = array_merge($headers, $this->sign($str)); $httpRequest->addHeaders($r); $httpRequest->send(); if ($httpRequest->getResponseCode() == 401) { throw new Exception("Failed to authenticate as {$userId}. Ensure that your node_name and client key are correct."); } if ($httpRequest->getResponseCode() == 404) { throw new Exception("Client not found or parameters are not valid"); } else { if ($httpRequest->getResponseCode() <= 205) { $data = $httpRequest->getResponseData(); $retval = $data['body'] ? json_decode($data['body']) : true; } else { if ($httpRequest->getResponseCode() > 400) { $data = $httpRequest->getResponseData(); $msg = $data['body'] ? json_decode($data['body']) : ""; if (is_array($msg->error)) { $msg = $msg->error[0]; } elseif ($msg->error) { $msg = $msg->error; } else { $msg = "Unknown error. Error code: {$httpRequest->getResponseCode()}"; } throw new Exception("Request to chef server failed with error: {$msg} ({$method} {$path})"); } else { throw new Exception("Unexpected situation. Response code {$httpRequest->getResponseCode()}"); } } } return $retval; }
public function actionRegister() { $r = new \HttpRequest('https://agg.cipo.rnp.br/dds/subscriptions', \HttpRequest::METH_POST); $r->addHeaders(array('Accept-encoding' => 'application/xml;charset=utf-8', 'Content-Type' => 'application/xml;charset=utf-8')); $r->setBody('<?xml version="1.0" encoding="UTF-8"?><tns:subscriptionRequest xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:tns="http://schemas.ogf.org/nsi/2014/02/discovery/types"> <requesterId>urn:ogf:network:cipo.ufrgs.br:2014:nsa:meican</requesterId> <callback>http://meican-cipo.inf.ufrgs.br/meican2/web/topology/service/discovery/notification</callback> <filter> <include> <event>All</event> </include> </filter> </tns:subscriptionRequest>'); $r->send(); Yii::trace($r->getResponseCode() . " " . $r->getResponseBody()); return ""; }
public function testRemoveUsersCapabilities() { $a = array('RequestMethod' => 'RemoveUserCapabilities', 'OwnerID' => 'efb00dbb-d4ab-46dc-aebc-4ba83288c3c0'); $r = new HttpRequest($this->server_url, HttpRequest::METH_POST); $r->addPostFields($a); $r->send(); echo $r->getRawRequestMessage(); echo "\n"; echo $r->getRawResponseMessage(); echo "\n"; $this->assertEquals(200, $r->getResponseCode()); }
public function request($command, $args = array(), $responseCmd = null) { if (empty($command)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(NO_COMMAND_MSG, NO_COMMAND); } if (!is_array($args)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(sprintf(WRONG_REQUEST_ARGS_MSG, $args), WRONG_REQUEST_ARGS); } foreach ($args as $key => $value) { if ($value == "") { unset($args[$key]); } // Workaround for zones. Doesn't work in uCLoud becuase listZones not supported if ($key == 'zoneid' && $value != '' && $this->platformName != 'ucloud') { if (!$this->zonesCache) { foreach ($this->listZones() as $zone) { $this->zonesCache[$zone->name] = $zone->id; } } if ($this->zonesCache[$value]) { $args[$key] = $this->zonesCache[$value]; } else { throw new Scalr_Service_Cloud_Cloudstack_Exception("Availability zone '{$value}' no longer supported"); } } } // Building the query $args['apikey'] = $this->apiKey; $args['command'] = $command; $args['response'] = "json"; ksort($args); $query = http_build_query($args); $query = str_replace("+", "%20", $query); $query .= "&signature=" . $this->getSignature(strtolower($query)); // var_dump($query); $httpRequest = new HttpRequest(); $httpRequest->setMethod(HTTP_METH_GET); $url = $this->endpoint . "?" . $query; $httpRequest->setOptions(array("redirect" => 2, "useragent" => "Scalr", 'timeout' => 10, 'connecttimeout' => 10)); $httpRequest->setUrl($url); $httpRequest->send(); $code = $httpRequest->getResponseCode(); $data = $httpRequest->getResponseData(); if (empty($data)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(NO_DATA_RECEIVED_MSG, NO_DATA_RECEIVED); } //echo $data['body'] . "\n"; $result = @json_decode($data['body']); if (empty($result)) { throw new Scalr_Service_Cloud_Cloudstack_Exception("The server did not issue a json response ({$code}): {$data['body']}", NO_VALID_JSON_RECEIVED); } if (!$responseCmd) { $responseCmd = strtolower($command); } $propertyResponse = "{$responseCmd}response"; if (!property_exists($result, $propertyResponse)) { if (property_exists($result, "errorresponse") && property_exists($result->errorresponse, "errortext")) { throw new Scalr_Service_Cloud_Cloudstack_Exception($result->errorresponse->errortext); } else { throw new Scalr_Service_Cloud_Cloudstack_Exception(sprintf("Unable to parse the response ({$command}). Got code %d and message: %s", $code, $data['body'])); } } $response = $result->{$propertyResponse}; if ($code > 400) { /* * Request to cloudstack failed. general error (503) ( * apikey=very-secret-key& * command=deployVirtualMachine& * group=base-ubuntu1004-devel& * response=json& * serviceofferingid=85& * templateid=1670& * userdata=ZmFybWlkPTc2NDQ7cm9sZT1iYXNlLGNoZWY7ZXZlbnRoYW5kbGVydXJsPW15LnNjYWxyLm5ldDtoYXNoPTRjNGNmY2MxZWQ1NjlhO3JlYWxyb2xlbmFtZT1iYXNlLXVidW50dTEwMDQtZGV2ZWw7aHR0cHByb3RvPWh0dHBzO3JlZ2lvbj0yO3N6cl9rZXk9cDM2b2pXRGt0KytvK1RjSm1adXY0cmJMQWV3RUlPQ1hVM1lVWEtoMUFGdGtER1ZWYzVDV0lRPT07c2VydmVyaWQ9ZDM2YTBjOWUtZDJhMS00NTg0LTlkNjctN2E4YmE1NDMwMTM5O3AycF9wcm9kdWNlcl9lbmRwb2ludD1odHRwczovL215LnNjYWxyLm5ldC9tZXNzYWdpbmc7cXVlcnllbnZfdXJsPWh0dHBzOi8vbXkuc2NhbHIubmV0L3F1ZXJ5LWVudjtiZWhhdmlvcnM9YmFzZSxjaGVmO2Zhcm1fcm9sZWlkPTM2NzIzO3JvbGVpZD0zNjM3MTtlbnZfaWQ9MzQxNDtvd25lcl9lbWFpbD0%3D& * zoneid=2& * signature=PV02IqoAjmPlkAwd9TYCuAG4kp4%3D * ) */ throw new Exception("Request to cloudstack failed. {$response->errortext} ({$response->errorcode}) ({$query})"); } // list handling : most of lists are on the same pattern as listVirtualMachines : // { "listvirtualmachinesresponse" : { "virtualmachine" : [ ... ] } } preg_match('/list(\\w+)s/', strtolower($command), $listMatches); if (!empty($listMatches)) { $objectName = $listMatches[1]; if (property_exists($response, $objectName)) { $resultArray = $response->{$objectName}; if (is_array($resultArray)) { return $resultArray; } } else { // sometimes, the 's' is kept, as in : // { "listasyncjobsresponse" : { "asyncjobs" : [ ... ] } } $objectName = $listMatches[1] . "s"; if (property_exists($response, $objectName)) { $resultArray = $response->{$objectName}; if (is_array($resultArray)) { return $resultArray; } } } } return $response; }
protected function handleResponse(HttpRequest $r) { if ($r->getResponseCode() != 304) { if ($r->getResponseCode() != 200) { throw new Exception("Unexpected response code " . $r->getResponseCode()); } if (!strlen($body = $r->getResponseBody())) { throw new Exception("Received empty feed from " . $r->getUrl()); } $this->saveFeed($this->url2name($r->getUrl()), $body); } }
protected function sendRequest($uri, $method, $data = null) { try { $request = new HttpRequest("https://{$this->domain}.chargify.com{$uri}"); $request->setHeaders(array('Content-Type' => 'application/json', 'Authorization' => 'Basic ' . base64_encode("{$this->apiKey}:x"))); $request->setOptions(array('httpauth' => "{$this->apiKey}:x", 'timeout' => 45, 'connecttimeout' => 45, 'ssl' => array('version' => 1))); $request->setMethod(constant("HTTP_METH_{$method}")); if ($method == 'POST' && $data) { $request->setBody($data); } if ($method == 'PUT') { $request->addPutData($data); } } catch (Exception $e) { //TODO: throw $e; } $request->send(); if ($request->getResponseCode() == 500) { throw new Exception("Unable to proceed your request at the moment. Please try again later."); } if ($request->getResponseCode() == 404) { throw new Exception("Unable to proceed your request. Please contact billing@scalr.net to get help."); } return $request; }
protected function doDelete($action, array $data) { $module = empty($action) ? substr($this->module, 0, -1) : $this->module; if (strrpos($action, '.json') === false) { $action .= '.json'; } array_walk_recursive($data, 'Lupin_Model_API::encode'); $url = $this->hostname . $module . $action; $request = new HttpRequest($url, HTTP_METH_DELETE); $request->setQueryData($data); try { $request->send(); } catch (Exception $e) { return false; } $this->responseCode = $request->getResponseCode(); if ($request->getResponseCode() !== 200) { return false; } return $request->getResponseHeader(); }
protected function sendHttp($url, $method, $data = array()) { $request = new \HttpRequest($this->url . $url, $method); if ($data) { $request->setBody(json_encode($data, JSON_FORCE_OBJECT)); } try { $request->send(); if ($request->getResponseCode() >= 200 && $request->getResponseCode() < 300) { return $request->getResponseBody(); } } catch (\HttpException $ex) { throw new \Exception($ex->getMessage(), $ex->getCode()); } return ''; }