当前位置: 首页>>代码示例>>PHP>>正文


PHP HttpRequest::addHeaders方法代码示例

本文整理汇总了PHP中HttpRequest::addHeaders方法的典型用法代码示例。如果您正苦于以下问题:PHP HttpRequest::addHeaders方法的具体用法?PHP HttpRequest::addHeaders怎么用?PHP HttpRequest::addHeaders使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在HttpRequest的用法示例。


在下文中一共展示了HttpRequest::addHeaders方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: request

 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}");
     }
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:54,代码来源:Connection.php

示例2: OnStartForking

 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();
     }
 }
开发者ID:rickb838,项目名称:scalr,代码行数:55,代码来源:class.DBQueueEventProcess.php

示例3: testStoreAsset

 public function testStoreAsset()
 {
     $headers = array('X-Asset-Creator-Id' => (string) UUID::Random(), 'X-Asset-Id' => UUID::Zero);
     $r = new HttpRequest($this->server_url, HttpRequest::METH_POST);
     $r->addHeaders($headers);
     $r->AddPostFile(UUID::Random(), "eyewhite.tga", "image/tga");
     $r->send();
     $this->AssetSHA = sha1(file_get_contents('eyewhite.tga'));
     $this->assertEquals(201, $r->getResponseCode());
     if (file_exists('test.assetid')) {
         unlink('test.assetid');
     }
     file_put_contents('test.assetid', (string) UUID::Parse($r->getResponseHeader("X-Asset-Id")));
 }
开发者ID:QuillLittlefeather,项目名称:mgm-simiangrid,代码行数:14,代码来源:AssetServiceTests.php

示例4: _OssMethods

    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;
    }
开发者ID:RichardPear,项目名称:todo,代码行数:48,代码来源:MfsComponent.php

示例5: sendRequest

 /**
  * Perform the HTTP request.
  *
  * @param      \phpcouch\http\HttpRequest HTTP Request object
  *
  * @return     \phpcouch\http\HttpResponse  The response from the server
  *
  * @author     Simon Thulbourn <simon.thulbourn@bitextender.com>
  * @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;
 }
开发者ID:dzuelke,项目名称:phpcouch,代码行数:56,代码来源:HttpAdapter.php

示例6: http_connect

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);
    }
}
开发者ID:SuperQcheng,项目名称:exploit-database,代码行数:18,代码来源:7559.php

示例7: http_connect

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);
    }
}
开发者ID:SuperQcheng,项目名称:exploit-database,代码行数:20,代码来源:7611.php

示例8: Request

 private function Request($method, $uri, $request_body, $query_args, $headers = array())
 {
     $HttpRequest = new HttpRequest();
     $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)"));
     $timestamp = $this->GetTimestamp();
     $signature = $this->GetRESTSignature($timestamp);
     $HttpRequest->setUrl("https://cloudfront.amazonaws.com/" . self::API_VERSION . $uri);
     $HttpRequest->setMethod($method);
     if ($query_args) {
         $HttpRequest->addQueryData($query_args);
     }
     if ($request_body) {
         if ($method == constant("HTTP_METH_POST")) {
             $HttpRequest->setRawPostData(trim($request_body));
         } else {
             $HttpRequest->setPutData(trim($request_body));
         }
         $headers["Content-type"] = "text/xml";
     }
     $headers["Date"] = $timestamp;
     $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}";
     $HttpRequest->addHeaders($headers);
     try {
         $HttpRequest->send();
         //$info = $HttpRequest->getResponseInfo();
         $data = $HttpRequest->getResponseData();
         $this->LastResponseHeaders = $data['headers'];
         return $data['body'];
     } catch (Exception $e) {
         if ($e->innerException) {
             $message = $e->innerException->getMessage();
         } else {
             $message = $e->getMessage();
         }
         throw new Exception($message);
     }
 }
开发者ID:jasherai,项目名称:libwebta,代码行数:37,代码来源:class.AmazonCloudFront.php

示例9: signRequestV2

 /**
  * Signs request with signature version 2
  *
  * Only POST http method is supported
  *
  * @param   \HttpRequest $request Http request object
  * @throws  QueryClientException
  */
 protected function signRequestV2($request)
 {
     $time = time();
     //Gets the http method name
     $httpMethod = self::$httpMethods[$request->getMethod()];
     //Gets both host and path from the url
     $components = parse_url($request->getUrl());
     $common = ['AWSAccessKeyId' => $this->awsAccessKeyId, 'SignatureVersion' => '2', 'SignatureMethod' => 'HmacSHA1', 'Timestamp' => gmdate('Y-m-d\\TH:i:s', $time) . "Z"];
     $request->addPostFields($common);
     //Gets adjusted options
     $options = $request->getPostFields();
     //Calculating canonicalized query string
     ksort($options);
     $canonicalizedQueryString = '';
     foreach ($options as $k => $v) {
         $canonicalizedQueryString .= '&' . rawurlencode($k) . '=' . rawurlencode($v);
     }
     $canonicalizedQueryString = ltrim($canonicalizedQueryString, '&');
     $stringToSign = $httpMethod . "\n" . strtolower($components['host']) . "\n" . $components['path'] . "\n" . $canonicalizedQueryString;
     switch ($common['SignatureMethod']) {
         case 'HmacSHA1':
         case 'HmacSHA256':
             $algo = strtolower(substr($common['SignatureMethod'], 4));
             break;
         default:
             throw new QueryClientException('Unknown SignatureMethod ' . $common['SignatureMethod']);
     }
     $request->addPostFields(['Signature' => base64_encode(hash_hmac($algo, $stringToSign, $this->secretAccessKey, 1))]);
     $request->addHeaders(['X-Amz-Date' => gmdate(\DateTime::ISO8601, $time)]);
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:38,代码来源:QueryClient.php

示例10: request

 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));
     }
 }
开发者ID:rickb838,项目名称:scalr,代码行数:75,代码来源:UpdateClient.php

示例11: ajaxAction

 public function ajaxAction()
 {
     $this->view = new Lupin_View();
     $method = strtolower($this->_request->getParam('method'));
     $query_uri = trim($this->_request->getParam('query_uri'), '/ ');
     $url = $this->_request->getParam('url');
     $extraParams = $this->_request->getParam('param');
     $params = array('format' => $this->_request->getParam('format'));
     if (!empty($extraParams)) {
         foreach ($extraParams as $newParam) {
             $parms = explode('=', $newParam, 2);
             if (count($parms) > 1) {
                 list($key, $value) = $parms;
                 $params[$key] = $value;
             }
         }
     }
     $newMethod = HTTP_METH_GET;
     switch ($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;
     }
     $email = $this->_request->getParam('email');
     $pass = $this->_request->getParam('secretKey');
     $request_url = 'http://' . $url . '/' . $query_uri;
     $request = new HttpRequest($request_url, $newMethod);
     if ($email && $pass) {
         $encoded_auth = base64_encode($email . ':' . $pass);
         $request->addHeaders(array('Authorization' => 'Basic ' . $encoded_auth));
     }
     if ("post" == $method) {
         $request->addPostFields($params);
     } else {
         $request->addQueryData($params);
     }
     $res = $request->send();
     function collapseHeaders($headers)
     {
         $header_string = "";
         foreach ($headers as $name => $value) {
             $header_string .= $name . ": " . wordwrap($value, 45, "\n\t") . "\n";
         }
         return $header_string;
     }
     $responseInfo = $request->getResponseInfo();
     $response = array('request_url' => $responseInfo['effective_url'], 'response_headers' => collapseHeaders($res->getHeaders()), 'content' => $res->getBody(), 'status' => $res->getResponseCode(), 'method' => strtoupper($method), 'request_post_fields' => http_build_query(!is_null($postFields = $request->getPostFields()) ? $postFields : array()));
     $this->view->renderJson($response);
 }
开发者ID:jeremykendall,项目名称:spaz-api,代码行数:61,代码来源:TesterController.php

示例12: SendMessage

 /**
  * 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'));
         }
//.........这里部分代码省略.........
开发者ID:sacredwebsite,项目名称:scalr,代码行数:101,代码来源:class.DBServer.php

示例13: request

 /**
  * Perform any request
  *
  * @param   string method request method, e.g. HttpConstants::GET
  * @param   var parameters
  * @param   array headers default array()
  * @return  peer.http.HttpResponse response object
  * @throws  io.IOException
  */
 public function request($method, $parameters, $headers = array())
 {
     $r = new HttpRequest($this->url);
     $r->setMethod($method);
     $r->setParameters($parameters);
     $r->addHeaders($headers);
     return $this->send($r);
 }
开发者ID:melogamepay,项目名称:xp-framework,代码行数:17,代码来源:HttpConnection.class.php

示例14: array

$options = array();
$headers = array();
if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $headers['User-Agent'] = $_SERVER['HTTP_USER_AGENT'];
}
$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...
开发者ID:BackupTheBerlios,项目名称:biokemika-svn,代码行数:31,代码来源:proxy.php

示例15: signRequestV3

 /**
  * Signs request with signature v3
  *
  * @param   \HttpRequest   $request    Http request
  * @param   string         $subdomain  optional A subdomain
  */
 protected function signRequestV3($request, $subdomain = null)
 {
     $time = time();
     //Gets the http method name
     $httpMethod = self::$httpMethods[$request->getMethod()];
     $components = parse_url($request->getUrl());
     //Retrieves headers from request
     $options = $request->getHeaders();
     //Adding timestamp
     if (!isset($options['Date'])) {
         $options['Date'] = gmdate('r', $time);
         $request->addHeaders(['Date' => $options['Date']]);
     }
     //This also includes a mock objects which look like "Mock_S3QueryClient_d65a1dc1".
     if (preg_match('#(?<=[_\\\\])S3QueryClient(?=_|$)#', get_class($this))) {
         $amzHeaders = [];
         foreach ($options as $key => $val) {
             if (preg_match('/^x-amz-/i', $key)) {
                 //Saves amz headers which are used to sign the request
                 $amzHeaders[strtolower($key)] = $val;
             }
         }
         //S3 Client has a special Authorization string
         $canonicalizedAmzHeaders = '';
         if (!empty($amzHeaders)) {
             ksort($amzHeaders);
             foreach ($amzHeaders as $k => $v) {
                 $canonicalizedAmzHeaders .= $k . ':' . trim(preg_replace('/#( *[\\r\\n]+ *)+#/', ' ', $v)) . "\n";
             }
         }
         //Note that in case of multiple sub-resources, sub-resources must be lexicographically sorted
         //by sub-resource name and separated by '&'. e.g. ?acl&versionId=value.
         if (!empty($components['query'])) {
             $canonPath = $components['path'] . '?';
             parse_str($components['query'], $subresources);
             ksort($subresources);
             $allowed = $this->getAllowedSubResources();
             foreach ($subresources as $k => $v) {
                 if (in_array($k, $allowed)) {
                     $canonPath .= $k . ($v !== '' ? '=' . $v : '') . '&';
                 }
             }
             $canonPath = substr($canonPath, 0, -1);
         }
         $canonicalizedResource = (isset($subdomain) ? '/' . strtolower($subdomain) : '') . (isset($canonPath) ? $canonPath : $components['path'] . (!empty($components['query']) ? '?' . $components['query'] : '') . (!empty($components['fragment']) ? '#' . $components['fragment'] : ''));
         $stringToSign = $httpMethod . "\n" . (!empty($options['Content-Md5']) ? $options['Content-Md5'] . '' : '') . "\n" . (!empty($options['Content-Type']) ? $options['Content-Type'] . '' : '') . "\n" . (isset($amzHeaders['x-amz-date']) ? '' : $options['Date'] . "\n") . $canonicalizedAmzHeaders . $canonicalizedResource;
         $options['Authorization'] = "AWS " . $this->awsAccessKeyId . ":" . base64_encode(hash_hmac('sha1', $stringToSign, $this->secretAccessKey, 1));
     } else {
         $options['Authorization'] = "AWS " . $this->awsAccessKeyId . ":" . base64_encode(hash_hmac('sha1', $options['Date'], $this->secretAccessKey, 1));
     }
     $request->addHeaders(['Authorization' => $options['Authorization']]);
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:58,代码来源:S3QueryClient.php


注:本文中的HttpRequest::addHeaders方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。