本文整理汇总了PHP中HttpSocket::request方法的典型用法代码示例。如果您正苦于以下问题:PHP HttpSocket::request方法的具体用法?PHP HttpSocket::request怎么用?PHP HttpSocket::request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpSocket
的用法示例。
在下文中一共展示了HttpSocket::request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: request
/**
* Issues request and returns response as an array decoded according to the
* response's content type if the response code is 200, else triggers the
* $model->onError() method (if it exists) and finally returns false.
*
* @param mixed $model Either a CakePHP model with a request property, or an
* array in the format expected by HttpSocket::request or a string which is a
* URI.
* @return mixed The response or false
*/
public function request(&$model)
{
if (is_object($model)) {
$request = $model->request;
} elseif (is_array($model)) {
$request = $model;
} elseif (is_string($model)) {
$request = array('uri' => $model);
}
// Remove unwanted elements from request array
$request = array_intersect_key($request, $this->Http->request);
// Issues request
$response = $this->Http->request($request);
// Get content type header
$contentType = $this->Http->response['header']['Content-Type'];
// Extract content type from content type header
if (preg_match('/^([a-z0-9\\/\\+]+);\\s*charset=([a-z0-9\\-]+)/i', $contentType, $matches)) {
$contentType = $matches[1];
$charset = $matches[2];
}
// Decode response according to content type
switch ($contentType) {
case 'application/xml':
case 'application/atom+xml':
case 'application/rss+xml':
// If making multiple requests that return xml, I found that using the
// same Xml object with Xml::load() to load new responses did not work,
// consequently it is necessary to create a whole new instance of the
// Xml class. This can use a lot of memory so we have to manually
// garbage collect the Xml object when we've finished with it, i.e. got
// it to transform the xml string response into a php array.
App::import('Core', 'Xml');
$Xml = new Xml($response);
$response = $Xml->toArray(false);
// Send false to get separate elements
$Xml->__destruct();
$Xml = null;
unset($Xml);
break;
case 'application/json':
case 'text/javascript':
$response = json_decode($response, true);
break;
}
if (is_object($model)) {
$model->response = $response;
}
// Check response status code for success or failure
if (substr($this->Http->response['status']['code'], 0, 1) != 2) {
if (is_object($model) && method_exists($model, 'onError')) {
$model->onError();
}
return false;
}
return $response;
}
示例2: doSendInternalRequest
/**
* {@inheritdoc}
*/
protected function doSendInternalRequest(InternalRequestInterface $internalRequest)
{
$this->httpSocket->config['timeout'] = $this->getConfiguration()->getTimeout();
$request = array('version' => $this->getConfiguration()->getProtocolVersion(), 'redirect' => false, 'uri' => $url = (string) $internalRequest->getUrl(), 'method' => $internalRequest->getMethod(), 'header' => $this->prepareHeaders($internalRequest), 'body' => $this->prepareBody($internalRequest));
try {
$response = $this->httpSocket->request($request);
} catch (\Exception $e) {
throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $e->getMessage());
}
if (($error = $this->httpSocket->lastError()) !== null) {
throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $error);
}
return $this->getConfiguration()->getMessageFactory()->createResponse((int) $response->code, $response->reasonPhrase, ProtocolVersionExtractor::extract($response->httpVersion), $response->headers, BodyNormalizer::normalize($response->body, $internalRequest->getMethod()));
}
示例3: index
public function index() {
$HttpSocket = new HttpSocket ();
if (sizeof ( $this->params ['pass'] [0] ) != 1) {
throw new InvalidArgumentException ();
}
if (! empty ( $_SERVER ['PHP_AUTH_USER'] ) && ! empty ( $_SERVER ['PHP_AUTH_PW'] )) {
$HttpSocket->configAuth ( 'Basic', $_SERVER ['PHP_AUTH_USER'], $_SERVER ['PHP_AUTH_PW'] );
} elseif (isset ( $this->CurrentUser )) {
$HttpSocket->configAuth ( 'Basic', $this->Session->read ( 'Auth.User.Login' ), $this->Session->read ( 'Auth.User.Password' ) );
}
$this->response->type ( 'json' );
$request = array (
'method' => env ( 'REQUEST_METHOD' ),
'body' => $this->request->data,
'uri' => array (
'scheme' => Configure::read ( 'Api.scheme' ),
'host' => Configure::read ( 'Api.host' ),
'port' => 80,
'path' => Configure::read ( 'Api.path' ) . $this->params ['pass'] [0],
'query' => $this->params->query
)
);
$response = $HttpSocket->request ( $request );
$this->response->statusCode ( $response->code );
$this->response->body ( $response->body );
return $this->response;
}
示例4: _request
protected function _request($path, $request = array())
{
// preparing request
$request = Hash::merge($this->_request, $request);
$request['uri']['path'] .= $path;
// Read cached GET results
if ($request['method'] == 'GET') {
$cacheKey = $this->_generateCacheKey();
$results = Cache::read($cacheKey);
if ($results !== false) {
return $results;
}
}
// createding http socket object for later use
$HttpSocket = new HttpSocket();
// issuing request
$response = $HttpSocket->request($request);
// olny valid response is going to be parsed
if (substr($response->code, 0, 1) != 2) {
if (Configure::read('debugApis')) {
debug($request);
debug($response->body);
}
return false;
}
// parsing response
$results = $this->_parseResponse($response);
// cache and return results
if ($request['method'] == 'GET') {
Cache::write($cacheKey, $results);
}
return $results;
}
示例5: _request
protected function _request($method, $params = array(), $request = array())
{
// preparing request
$query = Hash::merge(array('method' => $method, 'format' => 'json'), $params);
$request = Hash::merge($this->_request, array('uri' => array('query' => $query)), $request);
// Read cached GET results
if ($request['method'] == 'GET') {
$cacheKey = $this->_generateCacheKey();
$results = Cache::read($cacheKey);
if ($results !== false) {
return $results;
}
}
// createding http socket object with auth configuration
$HttpSocket = new HttpSocket();
$HttpSocket->configAuth('OauthLib.Oauth', array('Consumer' => array('consumer_token' => $this->_config['key'], 'consumer_secret' => $this->_config['secret']), 'Token' => array('token' => $this->_config['token'], 'secret' => $this->_config['secret2'])));
// issuing request
$response = $HttpSocket->request($request);
// olny valid response is going to be parsed
if ($response->code != 200) {
if (Configure::read('debugApis')) {
debug($request);
debug($response->body);
}
return false;
}
// parsing response
$results = $this->_parseResponse($response);
// cache and return results
if ($request['method'] == 'GET') {
Cache::write($cacheKey, $results);
}
return $results;
}
示例6: _request
protected function _request($path, $request = array())
{
// preparing request
$request = Hash::merge($this->_request, $request);
$request['uri']['path'] .= $path;
if (isset($request['uri']['query'])) {
$request['uri']['query'] = array_merge(array('access_token' => $this->_config['token']), $request['uri']['query']);
} else {
$request['uri']['query'] = array('access_token' => $this->_config['token']);
}
// createding http socket object for later use
$HttpSocket = new HttpSocket(array('ssl_verify_host' => false));
// issuing request
$response = $HttpSocket->request($request);
// olny valid response is going to be parsed
if (substr($response->code, 0, 1) != 2) {
if (Configure::read('debugApis')) {
debug($request);
debug($response->body);
die;
}
return false;
}
// parsing response
$results = $this->_parseResponse($response);
if (isset($results['data'])) {
return $results['data'];
}
return $results;
}
示例7: request
/**
* Submits a request to Stripe. Requests are merged with default values, such as
* the api host. If an error occurs, it is stored in `$lastError` and `false` is
* returned.
*
* @param array $request Request details
* @return mixed `false` on failure, data on success
*/
public function request($request = array())
{
$this->lastError = null;
$this->request = array('uri' => array('host' => 'api.stripe.com', 'scheme' => 'https', 'path' => '/'), 'method' => 'GET');
$this->request = Set::merge($this->request, $request);
$this->request['uri']['path'] = '/v1/' . trim($this->request['uri']['path'], '/');
$this->Http->configAuth('Basic', $this->config['api_key'], '');
try {
$response = $this->Http->request($this->request);
switch ($this->Http->response['status']['code']) {
case '200':
return json_decode($response, true);
break;
case '400':
$error = json_decode($response, true);
$this->lastError = $error['error']['message'];
return false;
break;
case '402':
$error = json_decode($response, true);
$this->lastError = $error['error']['message'];
return false;
break;
default:
$this->lastError = 'Unexpected error.';
CakeLog::write('stripe', $this->lastError);
return false;
break;
}
} catch (CakeException $e) {
$this->lastError = $e->message;
CakeLog::write('stripe', $e->message);
}
}
示例8: _request
/**
* Performs an API request to Basecamp
* @param string $url
* @param string $method
* @param array $options
* @return string
* @access protected
*/
protected function _request($url, $method = 'GET', $options = array())
{
// Extract our settings and create our HttpSocket
extract($this->settings);
$socket = new HttpSocket();
// Build, execute and return the response
return $socket->request(am(array('method' => $method, 'uri' => array('scheme' => 'http', 'host' => $account . '.' . 'campfirenow.com', 'path' => $url, 'user' => $token, 'pass' => 'X'), 'auth' => array('method' => 'Basic', 'user' => $token, 'pass' => 'X'), 'header' => array('User-Agent' => 'CakePHP CampfireComponent')), $options));
}
示例9: greet
function greet($peer_address = null, $peer_port = null, $data = array())
{
if (!$peer_address || !$peer_port) {
return true;
}
App::import('Core', 'HttpSocket');
$HttpSocket = new HttpSocket();
$req = array('method' => 'POST', 'uri' => array('scheme' => 'http', 'host' => $peer_address, 'port' => $peer_port, 'path' => '/peers/hello'), 'header' => array('User-Agent' => 'Gitrbug/0.2'), 'body' => array('data' => $data));
$res = $HttpSocket->request($req);
return json_decode($res, true);
}
示例10: updateMyIP
function updateMyIP()
{
$addr = $this->findByName('ip_addr', array('fields' => 'value'));
App::import('Core', 'HttpSocket');
$HttpSocket = new HttpSocket();
$res = $HttpSocket->request(array('method' => 'GET', 'uri' => array('scheme' => 'http', 'host' => 'ipinfodb.com', 'path' => '/ip_query.php', 'query' => 'output=json'), 'header' => array('User-Agent' => 'Gitrbug/0.2')));
$r = json_decode($res, true);
if (empty($addr)) {
$this->create();
$this->save(array('name' => 'ip_addr', 'value' => $r['Ip']));
} else {
$this->updateAll(array('value' => $r['Ip']), array('name' => 'ip_addr'));
}
return $r['Ip'];
}
示例11: handleRequest
/**
* Makes the HTTP Rest request
*
* @return void
* @author Rob Mcvey
**/
public function handleRequest($request)
{
// HttpSocket.
if (!$this->HttpSocket) {
$this->HttpSocket = new HttpSocket();
$this->HttpSocket->quirksMode = true;
// Amazon returns sucky XML
}
// Make request
try {
return $this->HttpSocket->request($request);
} catch (SocketException $e) {
// If error Amazon returns garbage XML and
// throws HttpSocket::_decodeChunkedBody - Could not parse malformed chunk ???
throw new AmazonS3Exception(__('Could not complete the HTTP request'));
}
}
示例12: run
public function run($data)
{
if (!$data['hash']) {
$this->err("Tried to run search without a hash!?");
debug($data);
return true;
}
if (!array_key_exists('from', $data)) {
Configure::load('gitrbug');
$data['from'] = array('host' => $this->Setting->readIP(), 'port' => Configure::read('gitrbug.port'));
}
if ($peer = $this->Peer->choosePeer($data)) {
$this->out(print_r($peer, true));
if (!array_key_exists('PeerTable', $data)) {
$data['PeerTable'] = array();
for ($i = 0; $i < 40; $i++) {
if (rand(0, 3) == 0) {
$data['PeerTable'][$this->Peer->_genuuid()] = $this->Peer->_genuuid();
}
}
} elseif (count($data['PeerTable']) > 64) {
return true;
// end of teh road
}
$my_id = $this->Setting->getPrivateId();
$data['PeerTable'][$my_id] = $peer['Peer']['id'];
asort($data['PeerTable']);
App::import('Core', 'HttpSocket');
$HttpSocket = new HttpSocket();
$req = array('method' => 'POST', 'uri' => array('scheme' => 'http', 'host' => $peer['Peer']['ip'], 'port' => $peer['Peer']['port'], 'path' => '/peers/search'), 'header' => array('User-Agent' => 'Gitrbug/0.2'), 'body' => array('data' => json_encode($data)));
$res = $HttpSocket->request($req);
$r = json_decode($res, true);
if ($r = "success") {
$this->Peer->read(null, $peer['Peer']['id']);
$this->Peer->data['Peer']['score'] = $this->Peer->data['Peer']['score'] - 10;
$this->Peer->save();
$this->Peer->Tag->updateAll(array('Tag.score' => 'Tag.score - 10'), array('Tag.name' => am($data['hash'], $data['tags']), 'Tag.entity_id' => $peer['Peer']['id']));
}
debug($data);
$this->out(print_r($res, true));
return true;
} else {
// discard silently
return true;
}
}
示例13: _getServerInformation
/**
* Retrieve information about the authentication
*
* @param HttpSocket $http Http socket instance.
* @param array &$authInfo Authentication info.
* @return bool
*/
protected static function _getServerInformation(HttpSocket $http, &$authInfo)
{
$originalRequest = $http->request;
$http->configAuth(false);
$http->request($http->request);
$http->request = $originalRequest;
$http->configAuth('Digest', $authInfo);
if (empty($http->response['header']['WWW-Authenticate'])) {
return false;
}
preg_match_all('@(\\w+)=(?:(?:")([^"]+)"|([^\\s,$]+))@', $http->response['header']['WWW-Authenticate'], $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$authInfo[$match[1]] = $match[2];
}
if (!empty($authInfo['qop']) && empty($authInfo['nc'])) {
$authInfo['nc'] = 1;
}
return true;
}
示例14: request
/**
* Overrides HttpSocket::request() to handle cases where
* $request['auth']['method'] is 'OAuth'.
*
* @param array $request As required by HttpSocket::request(). NOTE ONLY
* THE ARRAY TYPE OF REQUEST IS SUPPORTED
* @return array
*/
public function request($request = array())
{
// If the request does not need OAuth Authorization header, let the parent
// deal with it.
if (!isset($request['auth']['method']) || $request['auth']['method'] != 'OAuth') {
return parent::request($request);
}
// Generate the OAuth Authorization Header content for this request from the
// request data and add it into the request's Authorization Header. Note, we
// don't just add the header directly in the request variable and return the
// whole thing from the authorizationHeader() method because in some cases
// we may not want the authorization header content in the request's
// authorization header, for example, OAuth Echo as used by Twitpic and
// Twitter includes an Authorization Header as required by twitter's verify
// credentials API in the X-Verify-Credentials-Authorization header.
$request['header']['Authorization'] = $this->authorizationHeader($request);
// Now the Authorization header is built, fire the request off to the parent
// HttpSocket class request method that we intercepted earlier.
return parent::request($request);
}
示例15: edit
function edit($id = null)
{
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid getter', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->Getter->save($this->data)) {
App::import('Core', 'HttpSocket');
$HttpSocket = new HttpSocket();
$request = array('method' => 'POST', 'uri' => array('scheme' => 'http', 'host' => 'localhost', 'port' => 3000, 'user' => null, 'pass' => null, 'path' => '/addInterval/', 'query' => null, 'fragment' => null), 'version' => '1.1', 'body' => json_encode(array('id' => (int) $this->data['Getter']['id'], 'interval' => (int) $this->data['Getter']['interval'], 'code' => $this->data['Getter']['code'])), 'header' => array('Content-type' => 'application/json'));
$results = $HttpSocket->request($request);
$this->Session->setFlash(__('The getter has been saved', true));
$this->redirect(array('action' => 'edit', $id));
} else {
$this->Session->setFlash(__('The getter could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->Getter->read(null, $id);
}
}