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


PHP HTTP_Request2::setAuth方法代码示例

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


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

示例1: getRequest

 /**
  * @param string $user
  * @param string $apiKey
  *
  * @return Request2
  */
 public function getRequest($user, $apiKey)
 {
     if ($this->req === null) {
         $this->req = new Request2();
         $this->req->setAdapter('curl')->setHeader('user-agent', 'Services_Librato');
     }
     $this->req->setAuth($user, $apiKey);
     return $this->req;
 }
开发者ID:till,项目名称:services_librato,代码行数:15,代码来源:Librato.php

示例2: request

 private function request($method, $path, $params = array())
 {
     $url = $this->api . rtrim($path, '/') . '/';
     if (!strcmp($method, "POST")) {
         $req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
         $req->setHeader('Content-type: application/json');
         if ($params) {
             $req->setBody(json_encode($params));
         }
     } else {
         if (!strcmp($method, "GET")) {
             $req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
             $url = $req->getUrl();
             $url->setQueryVariables($params);
         } else {
             if (!strcmp($method, "DELETE")) {
                 $req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE);
                 $url = $req->getUrl();
                 $url->setQueryVariables($params);
             }
         }
     }
     $req->setAdapter('curl');
     $req->setConfig(array('timeout' => 30));
     $req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
     $req->setHeader(array('Connection' => 'close', 'User-Agent' => 'PHPPlivo'));
     $r = $req->send();
     $status = $r->getStatus();
     $body = $r->getbody();
     $response = json_decode($body, true);
     return array("status" => $status, "response" => $response);
 }
开发者ID:davidangelcb,项目名称:voice,代码行数:32,代码来源:plivo.php

示例3: getClient

 /**
  * Creates a HTTP client if none is set.
  *
  * @return \HTTP_Request2
  */
 public function getClient()
 {
     if (false === $this->client instanceof \HTTP_Request2) {
         $this->client = new \HTTP_Request2();
         $this->client->setConfig(array('adapter' => 'HTTP_Request2_Adapter_Curl', 'timeout' => 3, 'max_redirects' => 1));
     }
     $this->client->setAuth($this->publicKey, $this->privateKey);
     return $this->client;
 }
开发者ID:easybib,项目名称:services_oneall,代码行数:14,代码来源:OneAll.php

示例4: testDigestAuth

 public function testDigestAuth()
 {
     $this->request->getUrl()->setQueryVariables(array('user' => 'luser', 'pass' => 'qwerty'));
     $wrong = clone $this->request;
     $this->request->setAuth('luser', 'qwerty', HTTP_Request2::AUTH_DIGEST);
     $response = $this->request->send();
     $this->assertEquals(200, $response->getStatus());
     $wrong->setAuth('luser', 'password', HTTP_Request2::AUTH_DIGEST);
     $response = $wrong->send();
     $this->assertEquals(401, $response->getStatus());
 }
开发者ID:SuhitNarayan,项目名称:SuhitNarayan-SEMANTICTECH,代码行数:11,代码来源:CommonNetworkTest.php

示例5: postArticle

 /**
  * 記事を投稿する.
  *
  * @param string $title 記事タイトル
  * @param string $text 記事本文
  * @param string $category 記事カテゴリ
  * @return string $res 結果
  */
 public function postArticle($title, $text, $category)
 {
     try {
         $req = new HTTP_Request2();
         $req->setUrl(self::ROOT_END_POINT . $this->liveDoorId . "/" . self::END_POINT_TYPE_ARTICLE);
         $req->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false));
         $req->setMethod(HTTP_Request2::METHOD_POST);
         $req->setAuth($this->liveDoorId, $this->atomPubPassword);
         $req->setBody($this->createBody($title, $text, $category));
         $req->setHeader('Expect', '');
         $res = $req->send();
     } catch (HTTP_Request2_Exception $e) {
         die($e->getMessage());
     } catch (Exception $e) {
         die($e->getMessage());
     }
     return $res;
 }
开发者ID:seiyaan,项目名称:LiveDoorBlogAtomPub,代码行数:26,代码来源:LiveDoorBlogAtomPub.php

示例6: requestToPostMethod

 public static function requestToPostMethod($argURL, $argParams = NULL, $argFiles = NULL, $argTimeOut = 60)
 {
     $HttpRequestObj = new HTTP_Request2();
     $urls = parse_url($argURL);
     if (isset($urls["user"]) && isset($urls["pass"])) {
         $HttpRequestObj->setAuth($urls["user"], $urls["pass"]);
     }
     if (isset($urls["port"])) {
         $url = $urls["scheme"] . '://' . $urls["host"] . ':' . $urls["port"];
     } else {
         $url = $urls["scheme"] . '://' . $urls["host"];
     }
     if (isset($urls["path"])) {
         $url .= $urls["path"];
     }
     $HttpRequestObj->setUrl($url);
     $HttpRequestObj->setMethod(HTTP_Request2::METHOD_POST);
     if ('https' === $urls["scheme"]) {
         $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut, 'adapter' => 'HTTP_Request2_Adapter_Curl', 'ssl_verify_peer' => FALSE, 'ssl_verify_host' => FALSE));
     } else {
         $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut));
     }
     if (is_array($argParams)) {
         foreach ($argParams as $key => $value) {
             $HttpRequestObj->addPostParameter($key, $value);
         }
     }
     // ファイルをアップロードする場合
     if (is_array($argFiles)) {
         foreach ($argFiles as $key => $value) {
             $HttpRequestObj->addUpload($key, $value);
         }
     }
     // リクエストを送信
     $response = $HttpRequestObj->send();
     // レスポンスのボディ部を表示
     return $response;
 }
开发者ID:s-nakazawa,项目名称:UNICORN,代码行数:38,代码来源:GenericHttpRequest.class.php

示例7: main

 /**
  * Make the http request
  */
 public function main()
 {
     if (!isset($this->_url)) {
         throw new BuildException("Missing attribute 'url' set");
     }
     $request = new HTTP_Request2($this->_url);
     // set the authentication data
     if (!empty($this->_authUser)) {
         $request->setAuth($this->_authUser, $this->_authPassword, $this->_authScheme);
     }
     foreach ($this->_configData as $config) {
         $request->setConfig($config->getName(), $config->getValue());
     }
     foreach ($this->_headers as $header) {
         $request->setHeader($header->getName(), $header->getValue());
     }
     if ($this->_verbose) {
         $observer = new HTTP_Request2_Observer_Log();
         // set the events we want to log
         $observer->events = $this->_observerEvents;
         $request->attach($observer);
     }
     $response = $request->send();
     if ($this->_responseRegex !== '') {
         $matches = array();
         preg_match($this->_responseRegex, $response->getBody(), $matches);
         if (count($matches) === 0) {
             throw new BuildException('The received response body did not match the ' . 'given regular expression');
         } else {
             $this->log('The response body matched the provided regex.');
         }
     }
 }
开发者ID:RadioCampusFrance,项目名称:airtime,代码行数:36,代码来源:HttpRequestTask.php

示例8: simpleHttpRequest

 function simpleHttpRequest($url, $params, $method)
 {
     $req = new HTTP_Request2($url, $method, array('ssl_verify_peer' => false, 'ssl_verify_host' => false));
     //authorize
     $req->setAuth($this->user, $this->pass);
     if ($params) {
         //serialize the data
         $json = json_encode($params);
         $json ? $req->setBody($json) : false;
     }
     //set the headers
     $req->setHeader("Accept", "application/json");
     $req->setHeader("Content-Type", "application/json");
     $response = $req->send();
     if (PEAR::isError($response)) {
         return $response->getMessage();
     } else {
         return $response->getBody();
     }
 }
开发者ID:2Parale,项目名称:php-api-demo,代码行数:20,代码来源:2performant.php

示例9: _request

 /**
  * we use the Pear::\HTTP_Request2 for all the heavy HTTP protocol lifting.
  *
  * @param string $resource api-resource
  * @param string $method request method [default:"GET"]
  * @param array $data request data as associative array [default:array()]
  * @param array $headers optional request header [default:array()]
  *
  * @throws ConnectionException
  * @throws BadRequestError
  * @throws UnauthorizedError
  * @throws ForbiddenError
  * @throws ConflictDuplicateError
  * @throws GoneError
  * @throws InternalServerError
  * @throws NotImplementedError
  * @throws ThrottledError
  * @throws CCException
  *
  * @return string json encoded servers response
  */
 private function _request($resource, $method = \HTTP_Request2::METHOD_GET, $data = array(), $headers = array())
 {
     $url = $this->_url . $resource;
     $request = new \HTTP_Request2($url);
     $request->setConfig(array('ssl_verify_peer' => API::SSL_VERIFY_PEER, 'ssl_cafile' => realpath(dirname(__FILE__)) . '/cacert.pem'));
     $methods = array('options' => \HTTP_Request2::METHOD_OPTIONS, 'get' => \HTTP_Request2::METHOD_GET, 'head' => \HTTP_Request2::METHOD_HEAD, 'post' => \HTTP_Request2::METHOD_POST, 'put' => \HTTP_Request2::METHOD_PUT, 'delete' => \HTTP_Request2::METHOD_DELETE, 'trace' => \HTTP_Request2::METHOD_TRACE, 'connect' => \HTTP_Request2::METHOD_CONNECT);
     $request->setMethod($methods[strtolower($method)]);
     #
     # If the current API instance has a valid token we add the Authorization
     # header with the correct token.
     #
     # In case we do not have a valid token but email and password are
     # provided we automatically use them to add a HTTP Basic Authenticaion
     # header to the request to create a new token.
     #
     if ($this->_token) {
         $headers['Authorization'] = sprintf('cc_auth_token="%s"', $this->_token);
     } else {
         if ($this->_email && $this->_password) {
             $request->setAuth($this->_email, $this->_password, \HTTP_Request2::AUTH_BASIC);
         }
     }
     #
     # The API expects the body to be urlencoded. If data was passed to
     # the request method we therefore use urlencode from urllib.
     #
     if (!empty($data)) {
         if ($request->getMethod() == \HTTP_Request2::METHOD_GET) {
             $url = $request->getUrl();
             $url->setQueryVariables($data);
         } else {
             // works with post and put
             $request->addPostParameter($data);
             $request->setBody(http_build_query($data));
         }
     }
     #
     # We set the User-Agent Header to pycclib and the local version.
     # This enables basic statistics about still used pycclib versions in
     # the wild.
     #
     $headers['User-Agent'] = sprintf('phpcclib/%s', $this->_version);
     #
     # The API expects PUT or POST data to be x-www-form-urlencoded so we
     # also set the correct Content-Type header.
     #
     if (strtoupper($method) == 'PUT' || strtoupper($method) == 'POST') {
         $headers['Content-Type'] = 'application/x-www-form-urlencoded';
     }
     #
     # We also set the Content-Length and Accept-Encoding headers.
     #
     //$headers['Content-Length'] = strlen($body);
     $headers['Accept-Encoding'] = 'compress, gzip';
     #
     # Finally we fire the actual request.
     #
     foreach ($headers as $k => $v) {
         $request->setHeader(sprintf('%s: %s', $k, $v));
     }
     for ($i = 1; $i < 6; $i++) {
         try {
             $response = $request->send();
             return $this->_return($response);
         } catch (\HTTP_Request2_Exception $e) {
             # if we could not reach the API we wait 1s and try again
             sleep(1);
             # if we tried for the fifth time we give up - and cry a little
             if ($i == 5) {
                 throw new ConnectionException('Could not connect to API...');
             }
         }
     }
 }
开发者ID:cloudcontrol,项目名称:phpcclib,代码行数:95,代码来源:API.php

示例10: hit

 /**
  * Make a low-level web hit to this site, with authentication.
  * @param string $path URL fragment for something under the base path
  * @param array $params POST parameters to send
  * @param boolean $auth whether to include auth data
  * @return string
  * @throws Exception on low-level error conditions
  */
 protected function hit($path, $params = array(), $auth = false, $cookies = array())
 {
     $url = $this->basepath . '/' . $path;
     $http = new HTTP_Request2($url, 'POST');
     if ($auth) {
         $http->setAuth($this->username, $this->password, HTTP_Request2::AUTH_BASIC);
     }
     foreach ($cookies as $name => $val) {
         $http->addCookie($name, $val);
     }
     $http->addPostParameter($params);
     $response = $http->send();
     $code = $response->getStatus();
     if ($code < '200' || $code >= '400') {
         throw new Exception("Failed API hit to {$url}: {$code}\n" . $response->getBody());
     }
     return $response;
 }
开发者ID:sukhjindersingh,项目名称:PHInest-Solutions,代码行数:26,代码来源:remote-tests.php

示例11: White

<?php

require_once 'Hawk/LixiServiceClient.php';
require_once 'Log.php';
require_once 'HTTP/Request2/Observer/Log.php';
$log = Log::factory("console");
date_default_timezone_set('Australia/Adelaide');
$endpoint = 'http://127.0.0.1:3000/lixi/';
// $endpoint = 'http://functional-test.htw.com.au/lixi/';
// $endpoint = 'https://staging.htw.com.au/lixi/';
$request = new HTTP_Request2($endpoint);
$request->setAuth("User", "Pass", HTTP_Request2::AUTH_BASIC);
$request->setConfig('ssl_verify_peer', false);
$observer = new HTTP_Request2_Observer_Log($log);
$request->attach($observer);
$hawk = new Hawk_LixiServiceClient($request, $endpoint);
try {
    $hawk->quote('<?xml version="1.0" encoding="utf-8"?><!--Generated ValEx XML Valuation Transaction--> <!--$Id: LIXI_Common.php 82861 2013-03-04 21:40:06Z vpurohit $--> <ValuationTransaction ProductionData="No"><RevisionNumber LIXIVersion="1.4" LenderVersion="1.0" UserVersion="1.0" UserType="Valuer"></RevisionNumber><Identifier UniqueID="VXJ-000000549644" Type="VPMAssigned" Description="Valex Reference Number"></Identifier><Identifier UniqueID="N/A" Type="LenderAssigned"></Identifier><Date>2013-06-03</Date><Time>15:10:43+09:30</Time><Publisher><RelatedEntityRef RelatedID="VXV-000001"></RelatedEntityRef></Publisher><Audience><RelatedEntityRef RelatedID="VXV-000021"></RelatedEntityRef></Audience><Message><Identifier UniqueID="Dummy_Value" Type="VPMAssigned"></Identifier><MessageRelatesTo><Identifier UniqueID="VXJ-000000549644" Type="VPMAssigned"></Identifier><Identifier UniqueID="N/A" Type="LenderAssigned"></Identifier></MessageRelatesTo><MessageBody Type="Information"><Status Name="Initial"><Date>2013-06-03</Date><Time>15:40:43+10:00</Time></Status></MessageBody><ValuationType><Identifier UniqueID="Dummy_Value" Type="ValuerAssigned"></Identifier><FullRegistered InterestInProperty="Other" ValSubType="ShortForm"><SubTypeNote>API PropertyPro Report</SubTypeNote><RealEstate Status="Established" Construction="No" MortgageInsurance="No" Occupancy="OwnerPrimary" LandAreaHectares="0" Transaction="Refinancing"><Identifier UniqueID="12345" Type="VPMAssigned" Description="RP ID"></Identifier><Residential Type="FullyDetachedHouse"></Residential><EstimatedValue EstimateBasis="ApplicantEstimate">3075417</EstimatedValue><Location><Address><BuildingName></BuildingName><FloorNo></FloorNo><UnitNo></UnitNo><StreetNo>139</StreetNo><Street Type="Street">Brisbane</Street><City>BULIMBA</City><State Name="QLD"></State><Postcode>4171</Postcode><Country>AU</Country></Address><Title IsPrimaryTitle="Yes"></Title></Location></RealEstate><RequestDate><Date>2013-06-03</Date></RequestDate><DetailedComment><RelatedEntityRef RelatedID="Dummy_value"></RelatedEntityRef><Comment></Comment></DetailedComment><RequestedPriority Indicator="Normal"><Date>2013-06-05</Date><Time>15:10:22</Time></RequestedPriority><FeeSegment><Fee Amount="200.00" Description="PanelFee" Class="Valuer"><Identifier UniqueID="dummy_value" Type="VPMAssigned" Description="InvoiceNumber"></Identifier></Fee></FeeSegment><ResponseSupportingDoc DocAttached="No" RequestorToSight="No" DocType="Report"><Identifier UniqueID="VXDR-000000" Type="VPMAssigned"></Identifier></ResponseSupportingDoc><RiskAnalysis><RiskRating RatingType="Other" Rating="0-NotKnown"><Identifier UniqueID="ExtendedSellingPeriod" Type="VPMAssigned" Description="There are adverse marketability issues, that may require an extended selling period of more than 6 months."></Identifier><Comment></Comment></RiskRating><RiskRating RatingType="Other" Rating="0-NotKnown"><Identifier UniqueID="HighRiskOrNonResiPropType" Type="VPMAssigned" Description="The subject property comprises a higher risk or non residential property type."></Identifier><Comment></Comment></RiskRating><RiskRating RatingType="Other" Rating="0-NotKnown"><Identifier UniqueID="ExistingImprovements" Type="VPMAssigned" Description="There are essential repairs, incomplete works to the property and/or the property is currently under construction"></Identifier><Comment></Comment></RiskRating><RiskRating RatingType="Other" Rating="0-NotKnown"><Identifier UniqueID="HeritageLocationEnvironmental" Type="VPMAssigned" Description="Heritage, Location or Environmental Issues"></Identifier><Comment></Comment></RiskRating></RiskAnalysis><ValueComponent LandValue="0" ImprovementsValue="0" RecommendedSecurity="Yes" LikelyWeeklyUnfRental="0"><MarketValueAsIfComplete Type="SinglePoint" ValueFloor="0" ValueCeiling="0"><Description>Existing Property</Description></MarketValueAsIfComplete><EstimatedSettlement><Duration Units="Months"></Duration></EstimatedSettlement><Comment>Value Component</Comment><ExpectedSellingPeriodComment></ExpectedSellingPeriodComment></ValueComponent><SiteDetailResponse TitleSearched="No"><SiteArea></SiteArea><Neighbourhood></Neighbourhood><PropertyCharacteristics CurrentUse="Non-Residential" ExternalCondition="Unknown" InternalCondition="Unknown" InternalLayout="Unknown" MainBuilding="Yes" MineSubsidence="Yes" PCItems="" SiteArea="" StreetAppeal="Unknown"></PropertyCharacteristics></SiteDetailResponse></FullRegistered></ValuationType></Message><RelatedPartySegment><RelatedParty RelPartyType="ValuationPanelManager"><Identifier UniqueID="VXV-000001" Type="VPMAssigned"></Identifier><CompanyName BusinessName="Valuation Exchange"></CompanyName><Address><BuildingName>Workcover</BuildingName><FloorNo>11</FloorNo><UnitNo></UnitNo><StreetNo>100</StreetNo><Street Type="Street">Waymouth</Street><City>ADELAIDE</City><State Name="SA"></State><Postcode>5000</Postcode><Country>AU</Country></Address><WorkPhone><Phone><Fax></Fax></Phone><Phone><FixedPhone AreaCode="08">83735522</FixedPhone></Phone></WorkPhone><Email Type="Work">valuationplacement@valex.com.au</Email></RelatedParty><RelatedParty RelPartyType="ValuationFirm"><Identifier UniqueID="VXV-000021" Type="VPMAssigned"></Identifier><CompanyName BusinessName="Herron Todd White (Tasmania) Pty Ltd"></CompanyName><Address><BuildingName></BuildingName><FloorNo></FloorNo><UnitNo>Suite 2</UnitNo><StreetNo>23</StreetNo><Street Type="Street">Brisbane</Street><City>LAUNCESTON</City><State Name="TAS"></State><Postcode>7250</Postcode><Country>AU</Country></Address><WorkPhone><Phone><Fax AreaCode="03">63313392</Fax></Phone><Phone><FixedPhone AreaCode="03">63344997</FixedPhone></Phone></WorkPhone><Email Type="Work">admin.tasmania@htw.com.au</Email></RelatedParty><RelatedParty RelPartyType="Lender" RelPartyDescription="Commonwealth Bank of Australia Limited."><Identifier UniqueID="VXCL-008694" Type="VPMAssigned"></Identifier><CompanyName BusinessName="Commonwealth Bank of Australia"></CompanyName><PersonName><FirstName>Trevor</FirstName><Surname>Kay</Surname></PersonName><Address><BuildingName></BuildingName><FloorNo></FloorNo><UnitNo></UnitNo><StreetNo>48</StreetNo><Street Type="Place">Martin</Street><City>SYDNEY</City><State Name="NSW"></State><Postcode>2000</Postcode><Country>AU</Country></Address><WorkPhone><Phone><Fax AreaCode="02">83312547</Fax></Phone><Phone><FixedPhone>1300660052</FixedPhone></Phone></WorkPhone></RelatedParty><RelatedParty RelPartyType="Other" RelPartyDescription="Applicant"><Identifier UniqueID="VXC-0001247074" Type="VPMAssigned"></Identifier><PersonName><FirstName>Nigel</FirstName><Surname>Black</Surname></PersonName></RelatedParty><RelatedParty RelPartyType="Other" RelPartyDescription="Access Provider"><Identifier UniqueID="VXC-0001247075" Type="VPMAssigned"></Identifier><PersonName><FirstName>TR</FirstName><Surname>Resources Des</Surname></PersonName><WorkPhone><Phone><FixedPhone></FixedPhone></Phone><Phone><Fax></Fax></Phone></WorkPhone><HomePhone><Phone><FixedPhone>0412345678</FixedPhone></Phone><Phone><Mobile></Mobile></Phone></HomePhone></RelatedParty></RelatedPartySegment><vx:Job xmlns:vx="https://vx.valex.com.au/lixi/schema/vx/0.1/#" Purpose="Mortgage"><vx:Property Type="Dwelling"/></vx:Job></ValuationTransaction>');
} catch (Exception $e) {
    print_r($e->getMessage());
}
// print $hawk->__getLastRequest() . "\n\n";
// print $hawk->__getLastResponse() . "\n\n";
// print $hawk->__getLastRequestHeaders() . "\n\n";
// print $hawk->__getLastResponseHeaders() . "\n\n";
// $hawk->cancel("<xml>Hi</xml>");
// $hawk->quote("<xml>Hi</xml>");
// $hawk->update("<xml>Hi</xml>");
开发者ID:jvnill,项目名称:Hawk_LixiServiceClient,代码行数:28,代码来源:example.php

示例12: 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');
        $ssl         = $this->_request->getParam('ssl');
        $extraParams = $this->_request->getParam('param');

        $params      = array();

        $session_query_uri = '/' . substr($query_uri, 0, strrpos($query_uri, '.'));
        $test_history      = new Zend_Session_Namespace('test_history');
        $history           = $test_history->value;

        $history[$session_query_uri] = $this->getRequest()->getParams();

        $test_history->value = $history;

        if (!empty($extraParams)) {
            foreach ($extraParams as $newParam) {
                $parms                 = explode('=', $newParam, 2);
                if (count($parms) > 1) {
                    list($key, $value) = $parms;
                    $params[$key]      = $value;
                }
            }
        }

        require_once 'HTTP/Request2.php';

        $newMethod = HTTP_Request2::METHOD_GET;

        switch ($method) {
            case 'get':
                $newMethod = HTTP_Request2::METHOD_GET;
                break;
            case 'post':
                $newMethod = HTTP_Request2::METHOD_POST;
                break;
            case 'put':
                $newMethod = HTTP_Request2::METHOD_PUT;
                break;
            case 'delete':
                $newMethod = HTTP_Request2::METHOD_DELETE;
                break;
            case 'head':
                $newMethod = HTTP_Request2::METHOD_HEAD;

                break;
        }

        $email = $this->_request->getParam('email');
        $pass = $this->_request->getParam('secretKey');

        $request_url = 'http' . ($ssl == true ? 's' : '') . '://' . $url . '/' . $query_uri;

        $request = new HTTP_Request2($request_url, $newMethod);

        if ($email && $pass) {
            $request->setAuth($email, $pass, HTTP_Request2::AUTH_DIGEST);
            $request->setHeader(array(
                'Accept' => '*/*'
            ));
        }
        if ($method == 'post') {
            $request->addPostParameter($params);
        } else {
            $url = $request->getUrl();
            $url->setQueryVariables(array() + $params);
        }

        try {
            $res = $request->send();
        } catch (Exception $e) {
            return $this->view->renderJson(array(
                'request_url' => $request_url,
                'response_headers' => $this->collapseHeaders(array(
                    'error' => $e->getMessage())
                ),

                'content' => $e->getMessage(),
                'status' => 'Could not connect',
                'method' => strtoupper($method)
            ));
        }

        $response = array(
            'request_url'         => $request_url,
            'response_headers'    => $this->collapseHeaders($res->getHeader()),
            'content'             => $res->getBody(),
            'status'              => $res->getStatus(),
            'method'              => strtoupper($method),
        );

        $this->view->renderJson($response);
    }
开发者ID:reith2004,项目名称:frapi,代码行数:98,代码来源:TesterController.php

示例13: delete

 public function delete($url, $headers = array(), $auth = false)
 {
     $req = new HTTP_Request2($url);
     $req->setMethod(HTTP_Request2::METHOD_DELETE);
     $req->setHeader($headers);
     if ($auth) {
         $req->setAuth($auth['username'], $auth['password']);
     }
     //$req->setConfig('ssl_verify_peer', false);
     $response = $req->send();
     return $response;
 }
开发者ID:robinpaulson,项目名称:dataserver,代码行数:12,代码来源:http.inc.php

示例14: initSolrRequest

 /**
  * Initialize the Solr request object
  *
  * @param int $timeout Timeout in seconds (optional)
  *
  * @return void
  */
 protected function initSolrRequest($timeout = null)
 {
     global $configArray;
     if (!isset($this->request)) {
         $this->request = new HTTP_Request2($configArray['Solr']['update_url'], HTTP_Request2::METHOD_POST, ['ssl_verify_peer' => false]);
         if ($timeout !== null) {
             $this->request->setConfig('timeout', $timeout);
         }
         $this->request->setHeader('Connection', 'Keep-Alive');
         $this->request->setHeader('User-Agent', 'RecordManager');
         if (isset($configArray['Solr']['username']) && isset($configArray['Solr']['password'])) {
             $this->request->setAuth($configArray['Solr']['username'], $configArray['Solr']['password'], HTTP_Request2::AUTH_BASIC);
         }
     }
 }
开发者ID:grharry,项目名称:RecordManager,代码行数:22,代码来源:SolrUpdater.php

示例15: sendToCouchDb

 /**
  * Send data to CouchDB. This function dies on HTTP error and also if no
  * config.ini is found.
  *
  * @param array  $data  The object/document.
  * @param string $file  The filename of the log currently being crunched.
  * @param int    $count Which line are we at?
  *
  * @return void
  * @uses   \HTTP_Request2
  */
 public static function sendToCouchDb(array $data, $file, $count)
 {
     static $config;
     if ($config === null) {
         $config = parse_ini_file(self::$base . '/config.ini', true);
         if ($config === false) {
             echo "Couldn't read config.ini.";
             exit(1);
         }
     }
     static $req;
     if ($req === null) {
         require_once 'HTTP/Request2.php';
         $req = new \HTTP_Request2();
         $req->setAuth($config['couchdb']['user'], $config['couchdb']['pass']);
         $req->setMethod(\HTTP_Request2::METHOD_PUT);
     }
     $obj = (object) $data;
     $id = md5($obj->line);
     // generate _id
     try {
         $req->setUrl($config['couchdb']['host'] . "/{$id}");
         $req->setBody(json_encode($obj));
         $resp = $req->send();
         echo "\tDocument: {$id} (file: {$file}, line: {$count}), ";
         echo "Response: " . $resp->getStatus();
         if ($resp->getStatus() == 409) {
             echo " [duplicate]";
         }
         echo "\n";
         unset($resp);
         unset($obj);
         unset($data);
         unset($id);
     } catch (Exception $e) {
         echo "Error: " . $e->getMessage();
         exit(1);
     }
 }
开发者ID:pear,项目名称:PEAR_LogfileAnalysis,代码行数:50,代码来源:LogfileAnalysis.php


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