protected function sendPost($url, array $data = array()) { $this->request->setUrl($this->getUrl($url)); $this->request->setMethod(\HttpRequest::METH_POST); if (count($data)) { $this->request->setPostFields($data); } $this->request->send(); }
protected function doPost($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_POST); $request->setPostFields($data); try { $request->send(); } catch (Exception $e) { return false; } $this->responseCode = $request->getResponseCode(); if ($request->getResponseCode() !== 200) { return false; } $json = json_decode($request->getResponseBody()); if (!is_object($json) && !is_array($json)) { return false; } return $json; }
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()); } } }
/** * 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); }
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); } }
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 ($parameters['method'] == 'post') { $post_params = array(); parse_str($parameters['parameters'], $post_params); $h->setPostFields($post_params); } $h->send(); return $h->getResponseBody(); }
private function _OssMethods($action, $key, $files = false) { if (!$key || !$action) return; if ($action != 'DELETE' && $action != 'PUT') return; $options = array( 'useragent' => "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YINUOINFO API; Alexa Toolbar)", 'connecttimeout' => 120, 'timeout' => 120, 'redirect' => 10, ); if ($action == 'DELETE') { $r = new HttpRequest(self::OssBaseURL . 'delete.php?key=' . $key, HTTP_METH_GET); $r->setOptions($options); $r->addHeaders(array('Authorization' => 'Basic ' . base64_encode(self::US_UP_AUTHORIZATION))); try { $ret = $r->send()->getBody(); if ($ret == 'success') return 1; } catch (HttpException $e) { return 0; } } if ($action == 'PUT') { if (self::UseLocalFile && !APP_DEV){ $r = new HttpRequest(self::LocalOssBaseURL . 'local_upload.php', HTTP_METH_POST); $r->setPostFields(array('key' => $key,'localfile' => $files)); }else { $r = new HttpRequest(self::OssBaseURL . 'upload.php', HTTP_METH_POST); $r->setPostFields(array('key' => $key)); $r->addPostFile('file', $files, 'image/jpeg'); } $r->setOptions($options); $r->addHeaders(array('Authorization' => 'Basic ' . base64_encode(self::US_UP_AUTHORIZATION))); try { $ret = $r->send()->getBody(); if (preg_match("/OK/i", $ret)) return 1; } catch (HttpException $e) { return 0; } } return 0; }
function setSuggestTags($ce_name, $contentId) { global $cp_config; $url = $cp_config['tags_analizer_url']; $req = new HttpRequest($url, HttpRequest::METH_POST); // recupero todos los tags registrados $query = 'select v.id, v.label from #__custom_properties_values v '; $db = JFactory::getDBO(); $db->setQuery($query); $tagsDb = $db->loadObjectList(); $tagsRaw = array(); foreach ($tagsDb as $currentTag) { $tagsRaw[] = $currentTag->id; $tagsRaw[] = $currentTag->label; } $tags = implode(',', $tagsRaw); //$tags .= ',exposicion,hola,chau,termino'; $fields = $cp_config['tags_analizer_fields']; // preparo los datos a enviar $postData = array('id' => $contentId, 'content' => $ce_name, 'fields' => $fields, 'tags' => $tags); // print_r($postData); $req->setPostFields($postData); // envio la solicitud $rawResponse = $req->send(); // if ($rawResponse->getResponseCode() != 200){ // throw new Exception('we had a comunication problem. ' . $rawResponse->getResponseCode()); // } //echo '#### ' . $rawResponse->getResponseCode() . ' ####'; // recupero los tags $responseTags = $rawResponse->getBody(); $query = "insert into #__logs(info) values (concat('TAGS: ','{$responseTags}')) "; $db = JFactory::getDBO(); $db->setQuery($query); $db->query(); //echo '-------' . $responseTags . '------'; // parseo los tags y los guardo $this->_suggestList = explode(',', $responseTags); // print_r($this->_suggestList); }
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; }
<?php $r = new HttpRequest('http://dev.iworks.at/.print_request.php', HTTP_METH_POST); // if redirects is set to true, a single redirect is allowed; // one can set any reasonable count of allowed redirects $r->setOptions(array('cookies' => array('MyCookie' => 'has a value'), 'redirect' => true)); // common form data $r->setPostFields(array('name' => 'Mike', 'mail' => '*****@*****.**')); // add the file to post (form name, file name, file type) $r->addPostFile('image', 'profile.jpg', 'image/jpeg'); try { print $r->send()->getBody(); } catch (HttpException $e) { print $e; }
<?php $url = 'http://localhost/book/post-form-page.php'; $data = array("email" => "*****@*****.**", "display_name" => "LornaJane"); $request = new HttpRequest($url, HTTP_METH_POST); $request->setPostFields($data); $request->send(); $page = $request->getResponseBody(); echo $page;
$options['timeout'] = 30; # Compression? Don't use since we've got at least 100mbit bandwith, # so that isn't important # $options['compress'] = true; # Auto redirection handling? Nice, but doesn't work correctly so # we'll use our own implementation. # $options['redirect'] = 10; if (isset($_SERVER['HTTP_REFERER'])) { $options['referer'] = $conf->deproxify($_SERVER['HTTP_REFERER']); } $request->addHeaders($headers); $request->setOptions($options); // handle GET / POST requests and data if (!empty($_POST)) { $request->setMethod(HttpRequest::METH_POST); $request->setPostFields($_POST); } else { // GET Request $request->setMethod(HttpRequest::METH_GET); } // Cookie handling $request->enableCookies = true; $request->setCookies($_COOKIE); try { // HttpRequest can follow redirects automatically, but that // works strangely... $max_follow_redirects = 10; do { $response = $request->send(); if ($response->getResponseCode() >= 400) { // Error codes. Redirect client to error page so he
<?php $request = new HttpRequest(); $request->setUrl('http://mockbin.com/har'); $request->setMethod(HTTP_METH_POST); $request->setQueryData(array('foo' => array('bar', 'baz'), 'baz' => 'abc', 'key' => 'value')); $request->setHeaders(array('content-type' => 'application/x-www-form-urlencoded', 'accept' => 'application/json')); $request->setCookies(array('bar' => 'baz', 'foo' => 'bar')); $request->setContentType('application/x-www-form-urlencoded'); $request->setPostFields(array('foo' => 'bar')); 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/x-www-form-urlencoded')); $request->setContentType('application/x-www-form-urlencoded'); $request->setPostFields(array('foo' => 'bar', 'hello' => 'world')); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }