protected function makeApiRequest($type, $action, $params, $format = null, $creds = null, $useCache = true) { $config = load_class('Config'); $url = $config->config['base_url'] . 'api/' . urlencode($type); $useCache = false; // $creds === false means don't use credentials // $creds === null means use default credentials // $creds === array($user, $pass) otherwise (where pass is md5) // TODO pull this from config or make default user if ($creds === null) { // TODO find a better solution here !!! if (!array_key_exists('api_creds_user', $config->config)) { $config->config['api_creds_user'] = '******'; } if (!array_key_exists('api_creds_token', $config->config)) { $config->config['api_creds_token'] = '6228bd57c9a858eb305e0fd0694890f7'; } $creds = array($config->config['api_creds_user'], $config->config['api_creds_token']); } $req = new StdClass(); $req->request = new StdClass(); if (is_array($creds)) { $req->request->auth = new StdClass(); $req->request->auth->user = $creds[0]; $req->request->auth->pass = $creds[1]; } $req->request->action->type = $action; if (is_array($params)) { $req->request->action->data = new StdClass(); foreach ($params as $k => $v) { $req->request->action->data->{$k} = $v; } } $payload = $this->encode_request($req, $format); $cache_filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'joindin-test-' . md5($url . $payload); if ($useCache) { // Check for reading from cache if (file_exists($cache_filename) && is_readable($cache_filename)) { $cache_data = json_decode(file_get_contents($cache_filename)); if (time() < $cache_data->expires) { return $cache_data->payload; } } } $request = new HttpRequest($url, HttpRequest::METH_POST); $request->setBody($payload); if ($format == 'xml') { $request->setHeaders(array('Content-Type' => 'text/xml')); } else { // json is the default $request->setHeaders(array('Content-Type' => 'application/json')); } $response = $request->send(); if ($useCache) { $cache_data = json_encode(array('payload' => $response->getBody(), 'expires' => time() + 3600)); file_put_contents($cache_filename, $cache_data); // chmod( $cache_filename, 0777 ); } return $response->getBody(); }
/** * Send this HTTP request * * @throws Horde_Http_Exception * @return Horde_Http_Response_Base */ public function send() { if (!defined('HTTP_METH_' . $this->method)) { throw new Horde_Http_Exception('Method ' . $this->method . ' not supported.'); } $httpRequest = new HttpRequest((string) $this->uri, constant('HTTP_METH_' . $this->method)); $data = $this->data; if (is_array($data)) { $httpRequest->setPostFields($data); } else { if ($this->method == 'PUT') { $httpRequest->setPutData($data); } else { $httpRequest->setBody($data); } } $httpRequest->setOptions($this->_httpOptions()); try { $httpResponse = $httpRequest->send(); } catch (HttpException $e) { if (isset($e->innerException)) { throw new Horde_Http_Exception($e->innerException); } else { throw new Horde_Http_Exception($e); } } return new Horde_Http_Response_Peclhttp((string) $this->uri, $httpResponse); }
function cb_get_pois($params) { $base_addr = 'http://orion.lab.fi-ware.org:1026/v1/queryContext'; $limit = 1000; try { $orion_key = json_decode(file_get_contents('../orion_key.txt'))[0]; } catch (Exception $ex) { $orion_key = ""; } $search_area = cb_search_area($params); $ans = array(); $next = 0; $more = TRUE; try { while ($more) { $more = FALSE; $addr = $base_addr . '?'; if ($next > 0) { $addr = $addr . 'offset=' . $next . '&'; } $addr = $addr . 'limit=' . $limit; $next = $next + $limit; $http = new HttpRequest($addr, HTTP_METH_POST); $headers = array(); $headers['Content-Type'] = 'application/json'; $headers['Accept'] = 'application/json'; if ($orion_key != "") { $headers['X-Auth-Token'] = $orion_key; } $http->setHeaders($headers); $body = '{"entities":[{"type":"cie_poi","isPattern":"true","id":"cie_poi_*' . '"}],"attributes":["data"],"restriction":{"scopes":[{"type":"FI' . 'WARE::Location","value":' . $search_area . '}]}}'; $http->setBody($body); $respmsg = $http->send(); $resp_str = $respmsg->getBody(); $resp = json_decode($resp_str); if (property_exists($resp, 'contextResponses')) { $context_responses = $resp->contextResponses; foreach ($context_responses as $context_response) { $more = TRUE; $context_element = $context_response->contextElement; $id = $context_element->id; $uuid = substr($id, 8); $attributes = $context_element->attributes; foreach ($attributes as $attribute) { $name = $attribute->name; if ($name == 'data') { $encoded_value = $attribute->value; $json_value = rawurldecode($encoded_value); $ans[$uuid] = json_decode($json_value, TRUE); } } } } } } catch (Exception $e) { } return $ans; }
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(); } }
public static function execute($parameters) { $h = new \HttpRequest($parameters['server']['scheme'] . '://' . $parameters['server']['host'] . $parameters['server']['path'] . (isset($parameters['server']['query']) ? '?' . $parameters['server']['query'] : ''), static::$_methods[$parameters['method']], array('redirect' => 5)); if ( isset($parameters['header']) ) { $headers = array(); foreach ( $parameters['header'] as $header ) { list($key, $value) = explode(':', $header, 2); $headers[$key] = trim($value); } $h->setHeaders($headers); } if ( $parameters['method'] == 'post' ) { $h->setBody($parameters['parameters']); } if ( $parameters['server']['scheme'] === 'https' ) { $h->addSslOptions(array('verifypeer' => true, 'verifyhost' => true)); if ( isset($parameters['cafile']) && file_exists($parameters['cafile']) ) { $h->addSslOptions(array('cainfo' => $parameters['cafile'])); } if ( isset($parameters['certificate']) ) { $h->addSslOptions(array('cert' => $parameters['certificate'])); } } $result = ''; try { $h->send(); $result = $h->getResponseBody(); } catch ( \Exception $e ) { if ( isset($e->innerException) ) { trigger_error($e->innerException->getMessage()); } else { trigger_error($e->getMessage()); } } return $result; }
/** * Perform the HTTP request. * * @param \phpcouch\http\HttpRequest HTTP Request object * * @return \phpcouch\http\HttpResponse The response from the server * * @author Simon Thulbourn <*****@*****.**> * @since 1.0.0 */ public function sendRequest(\phpcouch\http\HttpRequest $request) { $internalRequest = new \HttpRequest($request->getDestination(), self::$httpMethods[$request->getMethod()]); // additional headers foreach ($request->getHeaders() as $key => $values) { foreach ($values as $value) { $this->headers[$key] = $value; } } if (!isset($this->headers['Content-Type'])) { $this->headers['Content-Type'] = 'application/json'; } if (null !== ($payload = $request->getContent())) { if (is_resource($payload)) { // This adapter has no real stream support as of now $payload = stream_get_contents($payload, -1, 0); } if ('PUT' == $request->getMethod()) { $internalRequest->setPutData($payload); } elseif ('POST' == $request->getMethod()) { $internalRequest->setBody($payload); $this->headers['Content-Length'] = strlen($payload); } } $internalRequest->addHeaders($this->headers); $message = new \HttpMessage($internalRequest->send()); $response = new HttpResponse(); $response->setStatusCode($message->getResponseCode()); if (!isset($response)) { throw new TransportException('Could not read HTTP response status line'); } foreach ($message->getHeaders() as $key => $value) { $response->setHeader($key, $value); } $response->setContent($message->getBody()); if ($message->getResponseCode() >= 400) { if ($message->getResponseCode() % 500 < 100) { // a 5xx response throw new HttpServerErrorException($message->getResponseStatus(), $message->getResponseCode(), $response); } else { // a 4xx response throw new HttpClientErrorException($message->getResponseStatus(), $message->getResponseCode(), $response); } } return $response; }
<?php $request = new HttpRequest(); $request->setUrl('https://exenzo.nl/api/v1/job/{job_id}'); $request->setMethod(HTTP_METH_PUT); $request->setHeaders(array('cache-control' => 'no-cache', 'content-type' => 'application/json', 'x-authorization' => 'ORGANISATION-API-TOKEN')); $request->setBody('{ "name" : "Test Organisation Ltd", "image" : "iVBORw0KGgoAAAANSUhEUg....AElFTkSuQmCC" }'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
<?php $request = new HttpRequest(); $request->setUrl('http://mockbin.com/har'); $request->setMethod(HTTP_METH_POST); $request->setHeaders(array('content-type' => 'application/json')); $request->setBody('{"number":1,"string":"f\\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}]}'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
$r = new HttpRequest('http://www.webservicex.net/globalweather.asmx', HttpRequest::METH_POST); //set headers $arrayHeadeFields = array("Host" => "www.webservicex.net", "SOAPAction" => "http://www.webserviceX.NET/GetWeather"); $r->setContentType("text/xml; charset=utf-8"); $r->setHeaders($arrayHeaderFields); //set the soap message for the request $xmlSoapMessage = '<?xml version="1.0" encoding="utf-8"?> <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>';
<?php $request = new HttpRequest(); $request->setUrl('http://mockbin.com/har'); $request->setMethod(HTTP_METH_POST); $request->setHeaders(array('content-type' => 'multipart/form-data; boundary=---011000010111000001101001')); $request->setBody('-----011000010111000001101001 Content-Disposition: form-data; name="foo"; filename="hello.txt" Content-Type: text/plain -----011000010111000001101001--'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
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 ''; }
function executeAsrRequest($url, $header, $audio) { // First, we need to set a few SSL options $sslOptions = array(); $sslOptions['verifypeer'] = "0"; $sslOptions['verifyhost'] = "0"; // Create an HttpRequest object $r = new HttpRequest($url, HttpRequest::METH_POST); // Set the SSL options, Headers, Content-Type, and body $r->setSslOptions($sslOptions); $r->setHeaders($header); $r->setContentType($header['Content-Type']); $r->setBody($audio); try { // Send the request $m = $r->send(); // Return the response object return $m; } catch (HttpException $ex) { // If an error occurs, just display it to the web page echo '<br><br><font color="red" Exception: ' . $ex . '</font><br><br>'; } }
/** * * adapt Request to HttpRequest * * {@link http://us.php.net/manual/en/http.constants.php * HTTP Predefined Constant} * * {@link http://us.php.net/manual/en/http.request.options.php * HttpRequest options} * * @throws InvalidArgumentException * @param Request $request * @param Endpoint $endpoint * @param HttpRequest * @return \HttpRequest */ public function toHttpRequest($request, $endpoint) { $url = $endpoint->getBaseUri() . $request->getUri(); $httpRequest = new \HttpRequest($url); $headers = array(); foreach ($request->getHeaders() as $headerLine) { list($header, $value) = explode(':', $headerLine); if ($header = trim($header)) { $headers[$header] = trim($value); } } // Try endpoint authentication first, fallback to request for backwards compatibility $authData = $endpoint->getAuthentication(); if (empty($authData['username'])) { $authData = $request->getAuthentication(); } if (!empty($authData['username']) && !empty($authData['password'])) { $headers['Authorization'] = 'Basic ' . base64_encode($authData['username'] . ':' . $authData['password']); } switch ($request->getMethod()) { case Request::METHOD_GET: $method = HTTP_METH_GET; break; case Request::METHOD_POST: $method = HTTP_METH_POST; if ($request->getFileUpload()) { $httpRequest->addPostFile('content', $request->getFileUpload(), 'application/octet-stream; charset=binary'); } else { $httpRequest->setBody($request->getRawData()); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/xml; charset=utf-8'; } } break; case Request::METHOD_HEAD: $method = HTTP_METH_HEAD; break; default: throw new InvalidArgumentException('Unsupported method: ' . $request->getMethod()); } $httpRequest->setMethod($method); $httpRequest->setOptions(array('timeout' => $endpoint->getTimeout(), 'connecttimeout' => $endpoint->getTimeout(), 'dns_cache_timeout' => $endpoint->getTimeout())); $httpRequest->setHeaders($headers); return $httpRequest; }
<?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); }
<?php $request = new HttpRequest(); $request->setUrl('http://mockbin.com/har'); $request->setMethod(HTTP_METH_POST); $request->setHeaders(array('content-type' => 'multipart/form-data; boundary=---011000010111000001101001')); $request->setBody('-----011000010111000001101001 Content-Disposition: form-data; name="foo" bar -----011000010111000001101001--'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
/** * Test an action * * This is the test action method. It test a specific action. * * @return void */ public function testAction() { $this->_helper->viewRenderer->setViewSuffix('txt'); // The options we are accepting for adding $options = new Zend_Console_Getopt(array('name|n=s' => 'Name of the action to call.', 'parameters|p=s' => 'Paramters to use. For example var1=val1&var2=val2', 'format|f=s' => 'Format to return. Defaults to XML.', 'method|m=s' => 'Method to use. Defaults to GET.', 'email|e=s' => 'Email or username to use.', 'secretkey|sk=s' => 'Secret key associated with email passed.', 'domain|d=s' => 'Domain to use, if not included will use default', 'query-uri|u=s' => 'Query uri to use. For example /testing/1', 'https|h' => 'Use https.')); try { $options->parse(); } catch (Zend_Console_Getopt_Exception $e) { $this->view->message = $e->getUsageMessage(); return; } if ($options->name == '') { $this->view->message = $options->getUsageMessage(); return; } $confModel = new Default_Model_Configuration(); if (!$confModel->getKey('api_url')) { $this->view->message = 'Remember you can set the default API domain name in your admin configuration.' . PHP_EOL; } if (!class_exists('HttpRequest')) { $this->view->message = 'HttpRequest class was not found the pecl_http (http://pecl.php.net/package/pecl_http) package is required to use the tester.' . PHP_EOL; return; } $action_name = $options->name; $params = $options->parameters; $format = $options->format; $method = $options->method; $email = $options->email; $password = $options->secretkey; $url = $options->domain; $ssl = $options->https; $query_uri = $options->getOption('query-uri'); if ($url == '') { $url = $confModel->getKey('api_url'); } if ($query_uri == '') { $actionModel = new Default_Model_Action(); $actions = $actionModel->getAll(); foreach ($actions as $action_details) { if ($action_details['name'] == $action_name) { $query_uri = $action_details['route']; } } } $newMethod = HTTP_METH_GET; switch (strtolower($method)) { case 'get': $newMethod = HTTP_METH_GET; break; case 'post': $newMethod = HTTP_METH_POST; break; case 'put': $newMethod = HTTP_METH_PUT; break; case 'delete': $newMethod = HTTP_METH_DELETE; break; case 'head': $newMethod = HTTP_METH_HEAD; break; } $request_url = 'http' . ($ssl !== null ? 's' : '') . '://' . $url . '/' . $query_uri . '.' . strtolower($format); $httpOptions = array(); if ($email && $password) { $httpOptions = array('headers' => array('Accept' => '*/*'), 'httpauth' => $email . ':' . $password, 'httpauthtype' => HTTP_AUTH_DIGEST); } $request = new HttpRequest($request_url, $newMethod, $httpOptions); if ("POST" == strtoupper($method)) { $request->setBody($params); } else { $request->setQueryData($params); } $res = $request->send(); $responseInfo = $request->getResponseInfo(); $this->view->request_url = $responseInfo['effective_url']; $this->view->response_header = $this->collapseHeaders($res->getHeaders()); $this->view->content = $res->getBody(); $this->view->status = $res->getResponseCode(); $this->view->method = isset($method) ? strtoupper($method) : 'GET'; $this->view->request_post_fields = $newMethod == HTTP_METH_POST ? $params : ''; }
<?php $request = new HttpRequest(); $request->setUrl('http://mockbin.com/har'); $request->setMethod(HTTP_METH_POST); $request->setHeaders(array('content-type' => 'text/plain')); $request->setBody('Hello World'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
public function put($url, $body) { $request = new HttpRequest(); $request->setMethod('PUT'); $request->setUrl($url); $request->setBody($body); $this->doRequest($request); }
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 ""; }
<?php $request = new HttpRequest(); $request->setUrl('https://exenzo.nl/api/v1/organisation/{organisation_id}'); $request->setMethod(HTTP_METH_PUT); $request->setHeaders(array('cache-control' => 'no-cache', 'content-type' => 'application/json', 'x-authorization' => 'ORGANISATION_API_TOKEN')); $request->setBody('{ "name" : "Test Organisation Ltd" }'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
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)); } }
<?php $request = new HttpRequest(); $request->setUrl('https://exenzo.nl/api/v1/organisation'); $request->setMethod(HTTP_METH_POST); $request->setHeaders(array('cache-control' => 'no-cache', 'content-type' => 'application/json', 'x-authorization' => 'ORGANISATION_API_TOKEN')); $request->setBody('{ "name" : "Test organisatie", "image" : "/9j/2wCEAAgGBgcGB....ace5r0qMf3dzx8S252ZgUlFJVnOLRRSUAf//Z" }'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }
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($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; }
/** * Send an event to the Datadog HTTP api. Potentially slow, so avoid * making many call in a row if you don't want to stall your app. * Requires PHP >= 5.3.0 and the PECL extension pecl_http * * @param string $title Title of the event * @param array $vals Optional values of the event. See * http://api.datadoghq.com/events for the valid keys * @return null **/ public static function event($title, $vals = array()) { // Assemble the request $vals['title'] = $title; // Convert a comma-separated string of tags into an array if (array_key_exists('tags', $vals) && is_string($vals['tags'])) { $tags = explode(',', $vals['tags']); $vals['tags'] = array(); foreach ($tags as $tag) { $vals['tags'][] = trim($tag); } } $body = json_encode($vals); // Added in PHP 5.3.0 // Get the url to POST to $url = static::$__datadogHost . static::$__eventUrl . '?api_key=' . static::$__apiKey . '&application_key=' . static::$__applicationKey; // Set up the http request. Need the PECL pecl_http extension $r = new HttpRequest($url, HttpRequest::METH_POST); $r->addHeaders(array('Content-Type' => 'application/json')); $r->setBody($body); // Send, suppressing and logging any http errors try { $r->send(); } catch (HttpException $ex) { error_log($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; }
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; }
/** * @return bool|null */ public function registerUser() { if (!$this->_plugin instanceof FeedPlugin) { return false; } $type = "pluginRegister"; $response = $this->getAction($this->getVersion()); $body = json_decode($response->getBody()); if (!isset($body->{$type})) { return $response; } else { $url = $body->{$type}; } $secret = $this->_plugin->getApiSecret(); $request = new HttpRequest(); $request->setUrl($url); $request->setHeaders($this->getSignHeader()); $request->setHeaders($this->_defaultHeader()); $request->setHeaders(array("X-HTTP-Method-Override" => "PUT")); $request->setHeaders(array("Expect" => '')); $request->setMethod('PUT'); $request->setBody(array("secret" => $secret, "bridgeUrl" => $this->_plugin->getBridgeUrl(), "urlParams" => $this->_plugin->getUrlParameters(), "possibleConfig" => $this->_plugin->getShopConfig(), "possibleFields" => $this->_plugin->getShopFields(), "shopName" => $this->_plugin->getShopName())); /** * @var HttpResponse $response */ $response = $this->_client->doRequest($request); return $response; }
/** * @return IHttpRequest */ public function factory() { $useFilter = !in_array(ini_get('filter.default'), ['', 'unsafe_raw']) || ini_get('filter.default_flags'); $post = $useFilter ? filter_input_array(INPUT_POST, FILTER_UNSAFE_RAW) : (empty($_POST) ? [] : $_POST); $cookies = $useFilter ? filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW) : (empty($_COOKIE) ? [] : $_COOKIE); $blacklist = '\\x09\\x0A\\x0D\\x20-\\x7E\\xA0-\\x{10FFFF}'; $chars = '~^[' . $blacklist . ']*+\\z~u'; if (!$this->binary) { $list = [&$post, &$cookies]; while (list($key, $source) = each($list)) { foreach ($source as $k => $v) { if (is_string($k) && (!preg_match($chars, $k) || preg_last_error())) { unset($list[$key][$k]); } else { if (is_array($v)) { $list[$key][$k] = $v; $list[] =& $list[$key][$k]; } else { $list[$key][$k] = (string) preg_replace('~[^' . $blacklist . ']+~u', '', $v); } } } } unset($list, $key, $source, $k, $v); } $uploadList = []; $list = []; if (!empty($_FILES)) { foreach ($_FILES as $k => $v) { if (!$this->binary && is_string($k) && (!preg_match($chars, $k) || preg_last_error())) { continue; } $v['@'] =& $uploadList[$k]; $list[] = $v; } } while (list(, $upload) = each($list)) { if (!isset($upload['name'])) { continue; } else { if (!is_array($upload['name'])) { if (!$this->binary && (!preg_match($chars, $upload['name']) || preg_last_error())) { $upload['name'] = ''; } if ($upload['error'] !== UPLOAD_ERR_NO_FILE) { $upload['@'] = new Upload($upload); } continue; } } foreach ($upload['name'] as $k => $foo) { if (!$this->binary && is_string($k) && (!preg_match($chars, $k) || preg_last_error())) { continue; } $list[] = ['name' => $upload['name'][$k], 'type' => $upload['type'][$k], 'size' => $upload['size'][$k], 'tmp_name' => $upload['tmp_name'][$k], 'error' => $upload['error'][$k], '@' => &$upload['@'][$k]]; } } $remoteAddress = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null; $remoteHost = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null; $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null; if ($method === 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']) && preg_match('#^[A-Z]+\\z#', $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; } $headers = []; foreach ($_SERVER as $k => $v) { if (strncmp($k, 'HTTP_', 5) == 0) { $k = substr($k, 5); } else { if (strncmp($k, 'CONTENT_', 8)) { continue; } } $headers[strtr($k, '_', '-')] = $v; } $httpRequest = new HttpRequest(); $httpRequest->setUrl(Url::getCurrent()); $httpRequest->setMethod($method); $httpRequest->setPost($post); $httpRequest->setUploadList($uploadList); $httpRequest->setCookies($cookies); $httpRequest->setHeaders($headers); $httpRequest->setRemoteAddress($remoteAddress); $httpRequest->setRemoteHost($remoteHost); $httpRequest->setBody(file_get_contents('php://input')); return $httpRequest; }
/** * * adapt Solarium_Client_Request to HttpRequest * * {@link http://us.php.net/manual/en/http.constants.php * HTTP Predefined Constant} * * @param Solarium_Client_Request $request * @param HttpRequest */ public function toHttpRequest($request) { $url = $this->getBaseUri() . $request->getUri(); $httpRequest = new HttpRequest($url); $headers = array(); foreach ($request->getHeaders() as $headerLine) { list($header, $value) = explode(':', $headerLine); if ($header = trim($header)) { $headers[$header] = trim($value); } } switch ($request->getMethod()) { case Solarium_Client_Request::METHOD_GET: $method = HTTP_METH_GET; break; case Solarium_Client_Request::METHOD_POST: $method = HTTP_METH_POST; $httpRequest->setBody($request->getRawData()); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/xml; charset=utf-8'; } break; case Solarium_Client_Request::METHOD_HEAD: $method = HTTP_METH_HEAD; break; default: throw new Solarium_Exception('Unsupported method: ' . $request->getMethod()); } $httpRequest->setMethod($method); $httpRequest->setOptions(array('timeout' => $this->getTimeout())); $httpRequest->setHeaders($headers); return $httpRequest; }