/** * @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; }
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); }
/** * 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; }
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()); }
/** * 記事を投稿する. * * @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; }
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; }
/** * 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.'); } } }
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(); } }
/** * 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...'); } } } }
/** * 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; }
<?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>");
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); }
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; }
/** * 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); } } }
/** * 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); } }
/** * Fetches a json response via HTTP request * @todo Support cookies (to allow login and similiar features) * @param string $url URL to get json from * @param array $data (optional) HTTP post data * @param boolean $secure (optional) Wheter to verify peer using SSL or not, default false * @param string $certificateFile (optional) Local certificate file for non public SSL certificates * @param array Set an optional HTTP Authentication method and supply its login credentials. * The supplied array must comply with the following structure: * <pre class="brush: php"> * $httpAuth = array( * 'httpAuthMethod' => 'none|basic|disgest', * 'httpAuthUsername' => '<username>', * 'httpAuthPassword' => '<password>', * ); * </pre> * @return mixed Decoded JSON on success, false otherwise */ public function getJson($url, $data = array(), $secure = false, $certificateFile = '', $httpAuth = array(), $files = array()) { $request = new \HTTP_Request2($url, \HTTP_Request2::METHOD_POST); if (!empty($httpAuth)) { switch ($httpAuth['httpAuthMethod']) { case 'basic': $request->setAuth($httpAuth['httpAuthUsername'], $httpAuth['httpAuthPassword'], \HTTP_Request2::AUTH_BASIC); break; case 'disgest': $request->setAuth($httpAuth['httpAuthUsername'], $httpAuth['httpAuthPassword'], \HTTP_Request2::AUTH_DIGEST); break; case 'none': default: break; } } foreach ($data as $name => $value) { $request->addPostParameter($name, $value); } if (!empty($files)) { foreach ($files as $fieldId => $file) { $request->addUpload($fieldId, $file); } } if ($this->sessionId !== null) { $request->addCookie(session_name(), $this->sessionId); } $request->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false, 'follow_redirects' => true, 'strict_redirects' => true)); $response = $request->send(); //echo '<pre>';var_dump($response->getBody());echo '<br /><br />'; $cookies = $response->getCookies(); foreach ($cookies as &$cookie) { if ($cookie['name'] === session_name()) { $this->sessionId = $cookie['value']; break; } } if ($response->getStatus() != 200) { \DBG::msg(__METHOD__ . ' Request failed! Status: ' . $response->getStatus()); \DBG::msg('URL: ' . $url); \DBG::dump($data); return false; } $body = json_decode($response->getBody()); if ($body === NULL) { \DBG::msg(__METHOD__ . ' failed!'); \DBG::dump($response->getBody()); } return $body; }
* except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ //PEAR package - needs to be installed: http://pear.php.net/package/HTTP_Request2/ require_once 'HTTP/Request2.php'; $openRegistryActivationAPI = new HTTP_Request2('https://dev-registry.rutgers.edu/api/v1/people/NETID/HR01/activation'); $openRegistryActivationAPI->setAuth('rats', 'RAT1234', HTTP_Request2::AUTH_BASIC); $openRegistryActivationAPI->setConfig(array('ssl_verify_peer' => false, 'ssl_verify_host' => false)); //Perform an HTTP POST request $openRegistryActivationAPI->setMethod(HTTP_Request2::METHOD_POST); $response = $openRegistryActivationAPI->send(); printf("Generate Activation Key call status: %d\n", $response->getStatus()); printf("New Activation Key resource Location: %s\n", $response->getHeader('Location')); printf("New Activation Key value: %s\n\n", array_pop(explode("/", $response->getHeader('Location')))); //Further process the activation key $openRegistryActivationAPI->setUrl($response->getHeader('Location')); verifyAndInvalidateActivationKey($openRegistryActivationAPI); function verifyAndInvalidateActivationKey($activationKeyResourceClient) { printf("Processing the activation key..............\n\n"); //Verify - HTTP GET $activationKeyResourceClient->setMethod(HTTP_Request2::METHOD_GET);
public function testDigestAuth() { $this->request->getUrl()->setQueryVariables(array('user' => 'luser', 'pass' => 'qwerty')); $wrong = clone $this->request; $observer = new EventSequenceObserver(array('sentHeaders', 'receivedHeaders')); $this->request->setAuth('luser', 'qwerty', HTTP_Request2::AUTH_DIGEST)->attach($observer); $response = $this->request->send(); $this->assertEquals(200, $response->getStatus()); $this->assertEquals(array('sentHeaders', 'receivedHeaders', 'sentHeaders', 'receivedHeaders'), $observer->sequence); $wrong->setAuth('luser', 'password', HTTP_Request2::AUTH_DIGEST); $response = $wrong->send(); $this->assertEquals(401, $response->getStatus()); }
<?php require 'HTTP/Request2.php'; $r = new HTTP_Request2('http://www.example.com/secrets.php'); $r->setAuth('david', 'hax0r', HTTP_Request2::AUTH_DIGEST); $page = $r->send()->getBody();
<?php require_once 'HTTP/Request2.php'; $Config = array('URI' => 'http://x13-net.ru/tunnel.php', 'Method' => HTTP_Request2::METHOD_POST, 'Login' => '', 'Password' => '', 'Head-In-Exclude' => array('Host', 'Connection', 'Cache-Control'), 'Head-Out-Exclude' => array('Server', 'X-Powered-By', 'Vary', 'Content-Encoding', 'Content-Length', 'Connection', 'Keep-Alive'), 'Log-Mode' => 2, 'Log-Path' => '/var/tmp/tunnel', 'Log-Header-File' => 'headers.log', 'Request-Config' => array('adapter' => 'HTTP_Request2_Adapter_Curl', 'connect_timeout' => 20, 'protocol_version' => '1.1', 'ssl_verify_peer' => false, 'ssl_verify_host' => false, 'ssl_cafile' => null, 'ssl_capath' => null, 'ssl_passphrase' => null)); $log = array(); register_shutdown_function('hlog'); $request = new HTTP_Request2($Config['URI'], $Config['Method']); $request->setConfig($Config['Request-Config']); if (!empty($Config['Login']) && !empty($Config['Password'])) { $request->setAuth($Config['Login'], $Config['Password']); } $headers = headers(); if ($Config['Log-Mode']) { $log[] = '--------------------------'; $log[] = '>>||>> ' . date('Y-m-d H:i:s'); $log[] = '--------------------------'; foreach ($headers as $name => $value) { $log[] = $name . ': ' . $value; } } $headers = exclude($headers, $Config['Head-In-Exclude']); foreach ($headers as $name => $value) { $request->setHeader($name, $value); } if (!empty($_POST)) { foreach ($_POST as $key => $value) { $request->addPostParameter($key, $value); } } // @see http://xpoint.ru/forums/programming/PHP/faq.xhtml#740 if (!empty($GLOBALS['HTTP_RAW_POST_DATA'])) {
function serendipity_request_url($uri, $method = 'GET', $contenttype = null, $data = null, $extra_options = null, $addData = null, $auth = null) { global $serendipity; require_once S9Y_PEAR_PATH . 'HTTP/Request2.php'; $options = array('follow_redirects' => true, 'max_redirects' => 5); if (is_array($extra_options)) { foreach ($extra_options as $okey => $oval) { $options[$okey] = $oval; } } serendipity_plugin_api::hook_event('backend_http_request', $options, $addData); serendipity_request_start(); if (version_compare(PHP_VERSION, '5.6.0', '<')) { // On earlier PHP versions, the certificate validation fails. We deactivate it on them to restore the functionality we had with HTTP/Request1 $options['ssl_verify_peer'] = false; } switch (strtoupper($method)) { case 'GET': $http_method = HTTP_Request2::METHOD_GET; break; case 'PUT': $http_method = HTTP_Request2::METHOD_PUT; break; case 'OPTIONS': $http_method = HTTP_Request2::METHOD_OPTIONS; break; case 'HEAD': $http_method = HTTP_Request2::METHOD_HEAD; break; case 'DELETE': $http_method = HTTP_Request2::METHOD_DELETE; break; case 'TRACE': $http_method = HTTP_Request2::METHOD_TRACE; break; case 'CONNECT': $http_method = HTTP_Request2::METHOD_CONNECT; break; default: case 'POST': $http_method = HTTP_Request2::METHOD_POST; break; } $req = new HTTP_Request2($uri, $http_method, $options); if (isset($contenttype) && $contenttype !== null) { $req->setHeader('Content-Type', $contenttype); } if (is_array($auth)) { $req->setAuth($auth['user'], $auth['pass']); } if ($data != null) { if (is_array($data)) { $req->addPostParameter($data); } else { $req->setBody($data); } } try { $res = $req->send(); } catch (HTTP_Request2_Exception $e) { serendipity_request_end(); return false; } $fContent = $res->getBody(); $serendipity['last_http_request'] = array('responseCode' => $res->getStatus(), 'effectiveUrl' => $res->getEffectiveUrl(), 'reasonPhrase' => $res->getReasonPhrase(), 'isRedirect' => $res->isRedirect(), 'cookies' => $res->getCookies(), 'version' => $res->getVersion(), 'header' => $res->getHeader(), 'object' => $res); serendipity_request_end(); return $fContent; }