예제 #1
0
파일: HttpTest.php 프로젝트: visor/nano
 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();
 }
 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());
 }
예제 #3
0
파일: HttpResponse.php 프로젝트: honzap/php
 /**
  * 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());
     }
 }
예제 #4
0
파일: Http.php 프로젝트: kingsj/core
 /**
  * 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);
 }
예제 #5
0
 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();
 }
예제 #6
0
 /**
  * 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);
 }
예제 #7
0
 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());
         }
     }
 }
예제 #8
0
 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);
     }
 }
예제 #9
0
 /**
  * RPC method proxy
  *
  * @param string $method RPC method name
  * @param array $params RPC method arguments
  * @return mixed decoded RPC response
  * @throws Exception
  */
 public function __call($method, array $params)
 {
     if (strlen($this->__namespace)) {
         $method = $this->__namespace . '.' . $method;
     }
     $this->__request->setContentType("text/xml");
     $this->__request->setRawPostData(xmlrpc_encode_request($method, $params, array("encoding" => $this->__encoding) + (array) $this->__options));
     $response = $this->__request->send();
     if ($response->getResponseCode() != 200) {
         throw new Exception($response->getResponseStatus(), $response->getResponseCode());
     }
     $data = xmlrpc_decode($response->getBody(), $this->__encoding);
     if (xmlrpc_is_fault($data)) {
         throw new Exception((string) $data['faultString'], (int) $data['faultCode']);
     }
     return $data;
 }
예제 #10
0
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;
}
예제 #11
0
 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') {
         $h->setRawPostData($parameters['parameters']);
     }
     $h->send();
     return $h->getResponseBody();
 }
예제 #12
0
/**
 * 2012年6月28日 携程 唐春龙 研发中心
 * 通过httpRequest调用远程webservice服务(返回一个XML)
 * @param $responseUrl 远程服务的地址
 * @param $requestXML 远程服务的参数请求体XML
 * @param 返回XML
 */
function httpRequestSoapData($responseUrl, $requestXML)
{
    try {
        $myhttp = new HttpRequest($responseUrl . "?WSDL", "POST");
        //--相对于API2.0固定
        $r_head = <<<BEGIN
<?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>
<Request xmlns="http://ctrip.com/">
<requestXML>
BEGIN;
        //--相对于API2.0固定
        $r_end = <<<BEGIN
</requestXML>
</Request>
</soap:Body>
</soap:Envelope>
BEGIN;
        //返回头--相对于API2.0固定
        $responseHead = <<<begin
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><RequestResponse xmlns="http://ctrip.com/"><RequestResult>
begin;
        //返回尾--相对于API2.0固定
        $responseEnd = <<<begin
</RequestResult></RequestResponse></soap:Body></soap:Envelope>
begin;
        $requestXML = str_replace("<", @"&lt;", $requestXML);
        $requestXML = str_replace(">", @"&gt;", $requestXML);
        $requestXML = $r_head . $requestXML . $r_end;
        //echo "<!--" . $requestXML ."-->";
        $myhttp->open();
        $myhttp->send($requestXML);
        $responseBodys = $myhttp->getResponseBody();
        //这里有可能有HEAD,要判断一下
        if (strpos($responseBodys, "Content-Type: text/xml; charset=utf-8")) {
            $coutw = $myhttp->responseBodyWithoutHeader;
        } else {
            $coutw = $responseBodys;
        }
        //$myhttp->responseBodyWithoutHeader;
        //$coutw=$myhttp->responseBodyWithoutHeader;
        $coutw = str_replace($responseHead, "", $coutw);
        //替换返回头
        $coutw = str_replace($responseEnd, "", $coutw);
        //替换返回尾
        $coutw = str_replace("&lt;", "<", $coutw);
        //将符号换回来
        $coutw = str_replace("&gt;", ">", $coutw);
        //将符号换回来
        // echo $coutw;
        return $coutw;
    } catch (SoapFault $fault) {
        return $fault->faultcode;
    }
}
    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();
    }
예제 #14
0
function returnWord()
{
    $r = new HttpRequest('http://randomword.setgetgo.com/get.php?len=6', "GET");
    $r->send();
    if ($r->getStatus() == 200) {
        return $_SESSION["word"] = $r->getResponseBody();
    } else {
        return "cannot generate music";
    }
}
예제 #15
0
 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();
     }
 }
예제 #16
0
 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}");
     }
 }
예제 #17
0
 /**
  * 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;
     }
 }
예제 #18
0
 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);
     }
 }
예제 #19
0
 function sendMessage($phonenumber, $message)
 {
     global $property;
     $request = new HttpRequest($property['MOVISTAR']['server'], HttpRequest::METH_GET);
     $request->addQueryData(array('shortcode' => $property['MOVISTAR']['shortcode'], 'msisdn' => $property['MOVISTAR']['msisdn'] . $phonenumber, 'telcoid' => $property['MOVISTAR']['telcoid'], 'encoding' => $property['MOVISTAR']['encoding'], 'smspart' => $property['MOVISTAR']['smspart'], 'udh' => $property['MOVISTAR']['udh'], 'body' => array($message), 'systemID' => $property['MOVISTAR']['systemID']));
     try {
         return $request->send();
     } catch (HttpException $httpe) {
         if (isset($httpe->innerException)) {
             echo $httpe->innerException->getMessage();
             exit;
         }
     }
     return null;
 }
예제 #20
0
 function post($url, $post_data)
 {
     $hr = new HttpRequest();
     $hr->setURL($url);
     $hr->setMethod('multipart');
     foreach ($post_data as $name => $value) {
         if ($name == 'file') {
             $hr->addFile(array('name' => 'file', 'path' => $value['path'], 'filename' => $value['filename']));
         } else {
             $hr->addQuery(array('key' => $name, 'value' => $value));
         }
     }
     $result = $hr->send();
     return $result;
 }
예제 #21
0
    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;
    }
예제 #22
0
 /**
  * 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;
 }
예제 #23
0
 private function Request($method, $uri, $args)
 {
     $HttpRequest = new HttpRequest();
     $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)"));
     $timestamp = $this->GetTimestamp();
     $URL = "queue.amazonaws.com";
     if ($this->Region != 'us-east-1') {
         $URL = "{$this->Region}.queue.amazonaws.com";
     }
     //EU URL: eu-west-1.queue.amazonaws.com
     $args['Version'] = self::API_VERSION;
     $args['SignatureVersion'] = 2;
     $args['SignatureMethod'] = "HmacSHA1";
     $args['Expires'] = $timestamp;
     $args['AWSAccessKeyId'] = $this->AWSAccessKeyId;
     ksort($args);
     foreach ($args as $k => $v) {
         $CanonicalizedQueryString .= "&{$k}=" . urlencode($v);
     }
     $CanonicalizedQueryString = trim($CanonicalizedQueryString, "&");
     $args['Signature'] = $this->GetRESTSignature(array($method, $URL, $uri, $CanonicalizedQueryString));
     $HttpRequest->setUrl("https://{$URL}{$uri}");
     $HttpRequest->setMethod(constant("HTTP_METH_{$method}"));
     if ($args) {
         $HttpRequest->addQueryData($args);
     }
     try {
         $HttpRequest->send();
         //$info = $HttpRequest->getResponseInfo();
         $data = $HttpRequest->getResponseData();
         $this->LastResponseHeaders = $data['headers'];
         $response = simplexml_load_string($data['body']);
         if ($response->Error) {
             throw new Exception($response->Error->Message);
         } else {
             return $response;
         }
     } catch (Exception $e) {
         if ($e->innerException) {
             $message = $e->innerException->getMessage();
         } else {
             $message = $e->getMessage();
         }
         throw new Exception($message);
     }
 }
예제 #24
0
 protected function makeApiRequest($type, $action, $params, $creds = null, $useCache = true)
 {
     // $creds === false means don't use credentials
     // $creds === null  means use default credentials
     // $creds === array($user, $pass) otherwise
     if ($creds === null) {
         $creds = array('kevin', '6228bd57c9a858eb305e0fd0694890f7');
     }
     $url = "http://lorna.rivendell.local/api/" . urlencode($type);
     $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 = json_encode($req);
     $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->addRawPostData($payload);
     $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();
 }
예제 #25
0
function http_connect($query)
{
    global $server;
    $headers = array('User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14', 'Referer' => $server);
    $res_http = new HttpRequest($server . "modules/auth/password_recovery.php?=1" . $query, HttpRequest::METH_GET);
    $res_http->addHeaders($headers);
    try {
        $response = $res_http->send()->getBody();
        if (eregi("page_header", $response)) {
            return 1;
        } else {
            return 0;
        }
    } catch (HttpException $exception) {
        print "[-] Not connected";
        exit(0);
    }
}
예제 #26
0
파일: BigGet.php 프로젝트: garybulin/php7
 /**
  * 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;
 }
예제 #27
0
파일: cashpot.php 프로젝트: nireno/Cashpot
/**
 * 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;
}
예제 #28
0
파일: Fetcher.php 프로젝트: cweiske/phinde
 /**
  * @return Retrieved HTTP response and elasticsearch document
  */
 public function fetch($url, $actions, $force = false)
 {
     $esDoc = $this->es->get($url);
     if (isset($esDoc->status->location) && $esDoc->status->location != '') {
         //TODO: what if location redirects change?
         $url = $esDoc->status->location;
         $esDoc = $this->es->get($url);
     }
     $types = array();
     foreach ($actions as $action) {
         $types = array_merge($action::$supportedTypes);
     }
     $types = array_unique($types);
     $req = new HttpRequest($url);
     $req->setHeader('accept', implode(',', $types));
     if (!$force && $esDoc && isset($esDoc->status->processed) && $esDoc->status->processed != '') {
         $nCrawlTime = strtotime($esDoc->status->processed);
         $req->setHeader('If-Modified-Since: ' . gmdate('r', $nCrawlTime));
     }
     $res = $req->send();
     if ($res->getStatus() === 304) {
         //not modified since last time, so don't crawl again
         Log::info("Not modified since last fetch");
         return false;
     } else {
         if ($res->getStatus() !== 200) {
             throw new \Exception("Response code is not 200 but " . $res->getStatus() . ", stopping");
         }
     }
     $effUrl = Helper::removeAnchor($res->getEffectiveUrl());
     if ($effUrl != $url) {
         $this->storeRedirect($url, $effUrl);
         $url = $effUrl;
         $esDoc = $this->es->get($url);
     }
     //FIXME: etag, hash on content
     $retrieved = new Retrieved();
     $retrieved->httpRes = $res;
     $retrieved->esDoc = $esDoc;
     $retrieved->url = $url;
     return $retrieved;
 }
예제 #29
0
function http_connect($query)
{
    global $server;
    $headers = array('User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14', 'Referer' => $server);
    $res_http = new HttpRequest($server . "modules/poll/?cc=62&PollID=1" . $query, HttpRequest::METH_GET);
    $res_http->addHeaders($headers);
    $t = mktime();
    try {
        $response = $res_http->send()->getBody();
        $t = mktime() - $t;
        if ($t > 4) {
            return 1;
        } else {
            return 0;
        }
    } catch (HttpException $exception) {
        print "[-] Not connected";
        exit(0);
    }
}
예제 #30
0
 public function getValue(DBFarmRole $dbFarmRole, Scalr_Scaling_FarmRoleMetric $farmRoleMetric)
 {
     $start_time = microtime(true);
     $HttpRequest = new HttpRequest();
     $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "Scalr (http://scalr.net) HTTPResponseTime Scaling Sensor", "connecttimeout" => 10));
     $HttpRequest->setUrl($farmRoleMetric->getSetting(self::SETTING_URL));
     $HttpRequest->setMethod(constant("HTTP_METH_GET"));
     try {
         $HttpRequest->send();
     } catch (Exception $e) {
         if ($e->innerException) {
             $message = $e->innerException->getMessage();
         } else {
             $message = $e->getMessage();
         }
         throw new Exception("HTTPResponseTime Scaling Sensor cannot get value: {$message}");
     }
     $retval = round(microtime(true) - $start_time, 2);
     return array($retval);
 }