本文整理汇总了PHP中HttpRequest类的典型用法代码示例。如果您正苦于以下问题:PHP HttpRequest类的具体用法?PHP HttpRequest怎么用?PHP HttpRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: _request
/** Generic request using the protocol:
* POSTs data & files, checks the magic header
* @param array $post Arbitrary data to POST
* @param array $files Files to upload: { name: path | [path, filename] | [path, filename, mimetype] }
* @return HttpResponse
* @throws RemScriptProtocolError
*/
function _request($post, $files)
{
# Prepare
$request = new HttpRequest($this->script_url, 'POST');
$request->mimicBrowser();
$request->headers['Connection'] = 'Close';
$request->post($post);
if (!empty($files)) {
foreach ($files as $name => $upload) {
list($path, $filename, $mimetype) = (array) $upload + array(null, null, null);
$request->upload($name, $path, $filename, $mimetype);
}
}
# Request
try {
$response = $request->open();
} catch (HttpRequestError $e) {
throw new RemScriptProtocolError('Request error: ' . $e->getMessage(), RemScriptProtocolError::REQUEST_ERROR, $e);
}
# Response: check code
if ($response->code != 200) {
throw new RemScriptProtocolError('Response code: ' . $response->code);
}
# Response: check magic
$expected = self::RESPONSE_MAGIC;
$actual = fread($response->f, strlen($expected));
if ($actual !== $expected) {
throw new RemScriptProtocolError('Wrong magic: ' . var_export($actual, 1));
}
# All okay
return $response;
}
示例2: __construct
function __construct(array $macros, IRouter $router, HttpRequest $req, I18n $i18n)
{
$this->router = $router;
$this->url = $req->getUrl();
$this->i18n = $i18n;
$this->macros = $this->macros + $macros;
}
示例3: executeCall
/**
* Execute a HTTP request to MusicBrainz server, errorMessage attribute is set in case of error.
*
* @return bool|string MusicBrainz informations or false on failure
*/
private function executeCall()
{
//request JSON output format
$this->setRequestedFormat('json');
//create a HTTP request object and call
require_once $_SERVER['DOCUMENT_ROOT'] . '/server/lib/HttpRequest.php';
$request = new HttpRequest();
if (!$request->execute($this->endpoint, 'GET', null, null, $this->queryParameters, $response, $responseHeaders)) {
$this->errorMessage = 'Error during request';
//error during HTTP request
return false;
}
//decode response
if ($this->format === 'json') {
$response = json_decode($response);
if (json_last_error() !== JSON_ERROR_NONE) {
$this->errorMessage = 'Invalid response received';
//error on JSON parsing
return false;
}
//return object
return $response;
}
//return false by default
return false;
}
示例4: request
public function request(array $params)
{
$request = new \HttpRequest($this->getTransmissionURL(), "POST");
$request->addBody(json_encode($params));
$this->client->attach($request);
return $this->client->send();
}
示例5: chooseController
/**
* @param HttpRequest $request
* @return string
*/
protected static function chooseController(HttpRequest $request)
{
/* Get controller name from the request */
$ctrl = $request->getController() . 'Controller';
/* If this controller exists - pass it or use default MainController */
return '\\application\\controllers\\' . (class_exists('\\application\\controllers\\' . $ctrl) ? $ctrl : 'MainController');
}
示例6: discover
/**
* Examine the URL, optionally looking for a specific service. If no
* service selection is done, all the services that the URL publishes
* will be returned.
*
* @param string $url The URL to explore
* @param string $service The service to look for
* @return array An array of the exposed services at the URL
*/
function discover($url, $services = null)
{
// Perform the query
$ret = new HttpRequest($url);
// Grab the data
$status = $ret->status();
$content = $ret->responseText();
$headers = $ret->headers();
$results = array();
// Enumerate the explorers
$explorers = config::get(Discovery::KEY_EXPLORERS, array());
foreach ($explorers as $explorer) {
// Discover the service and merge the results
$instance = new $explorer($url, $headers, $content);
$instance->discover();
if ($services) {
foreach ($instance->getAllServices() as $stype => $sdata) {
// Return the service if it matches the type.
if ($stype == $service) {
return $sdata;
}
}
} else {
// Merge the resultset otherwise
$results = array_merge($results, $instance->getAllServices());
}
}
// Return null if we were looking for a specific service
if ($services) {
return null;
}
return $results;
}
示例7: appendCustomAuthParams
/**
* Appends the necessary Custom Authentication credentials for making this authorized call
* @param HttpRequest $request The out going request to access the resource
*/
public static function appendCustomAuthParams($request)
{
$arrHeaders = $request->__get('headers');
$arrAuthHeader = array("X-Auth-Token" => Configuration::$APITOKEN);
$arrHeaders = array_merge($arrHeaders, $arrAuthHeader);
$request->__set('headers', $arrHeaders);
}
示例8: makeApiRequest
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'] = 'kevin';
}
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();
}
示例9: run
/**
* 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());
}
}
示例10: testDeleteAsset
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());
}
示例11: loginAction
public function loginAction()
{
$this->view->disable();
$http_request = new HttpRequest();
print_r($_SERVER);
$header = array('Host:106.37.195.128', 'User-Agent:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0', 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Referer:http://106.37.195.128/chinalifepcsfa/system/userLogin.do', 'Connection:keep-alive');
$data = 'platformType=0&userId=530123197902182620&password=sp182620';
$http_respone = $http_request->post('http://106.37.195.128/chinalifepcsfa/system/userLogin.do', $header, $data);
if (isset($http_respone->headers['Location'])) {
$location = $http_respone->headers['Location'];
$cookies = $http_respone->cookies;
$header2 = array('Host:106.37.195.128', 'User-Agent:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0', 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Referer:http://106.37.195.128/chinalifepcsfa/system/userLogin.do', 'Connection:keep-alive');
$http_respone2 = $http_request->get($location, $header2, $cookies);
preg_match('@href="(/chinalifepcsfa/user/electronicInsurance.do\\?.*)"@Ui', $http_respone2->content, $matches);
$entrance_href = 'http://106.37.195.128' . $matches[1];
$header3 = array('Host:106.37.195.128', 'User-Agent:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0', 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Connection:keep-alive');
$http_respone3 = $http_request->get($entrance_href, $header3, $cookies);
$final_url = $http_respone3->headers['Location'];
$_SESSION['emu_url'] = $final_url;
$final_header = array('Host:106.37.195.128:7011', 'User-Agent:Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0', 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Connection:keep-alive');
$final_http_response = $http_request->get($final_url, $final_header, $cookies);
$_SESSION['emu_cookies'] = $final_http_response->cookies;
} else {
echo json_encode(array('success' => false, 'err_msg' => '用户名或密码错误!'));
}
}
示例12: keyword_search
public function keyword_search($keyword)
{
// 從 Google 取得搜尋結果(HTML原始碼)
$keyword = urlencode($keyword);
$url = "https://www.google.com.tw/webhp?hl=zh-TW#hl=zh-TW&q={$keyword}&num=10";
$httpReq = new HttpRequest();
$httpReq->setUrl($url);
$content = $httpReq->submit();
unset($httpReq);
$results = array();
// 分析原始碼並取得每個項目
if (preg_match_all('/<!--m-->(.*?)<!--n-->/s', $content, $items)) {
$idx = 0;
foreach ($items[1] as $key => $item) {
$resultItem = new ResultItem();
$resultItem->sequence = $idx + 1;
$resultItem->title = preg_match('/<a .*?>(.*?)<\\/a>/s', $item, $res) ? trim($res[1]) : "";
$resultItem->link = urldecode(preg_match('/<h3 class="r"><a href="(.*?)".*?>.*?<\\/a>/s', $item, $res) ? trim($res[1]) : "");
$resultItem->description = preg_match('/<span class="st">(<span class="f">(.*?)<\\/span>)?(.*?)<\\/span>/s', $item, $res) ? trim($res[3]) : "";
$resultItem->save_date = str_replace(" - ", "", $res[2]);
if (trim($resultItem->link) == "") {
continue;
}
$idx++;
$results[] = $resultItem;
}
}
return $results;
}
示例13: request
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);
}
}
示例14: handleRequest
/**
* @param HttpRequest $request
* @return mixed
*/
public function handleRequest(HttpRequest $request)
{
if ($request->getCode() >= HttpRequest::HTTP_CLIENT_ERROR && $request->getCode() < HttpRequest::HTTP_SERVER_ERROR) {
echo 'Handling client error request';
} else {
parent::handleRequest($request);
}
}
示例15: index
public function index()
{
$http_request = new HttpRequest();
$http_response = $http_request->get('www.sina.com');
$http_response->headers;
$user = UserModel::findUserById('jkzleond@163.com');
$this->view->setVars(array('headers' => $http_response->headers, 'content' => htmlspecialchars($http_response->content), 'user' => $user));
}