本文整理汇总了PHP中Requests::request方法的典型用法代码示例。如果您正苦于以下问题:PHP Requests::request方法的具体用法?PHP Requests::request怎么用?PHP Requests::request使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Requests
的用法示例。
在下文中一共展示了Requests::request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: request
public function request($request_type = 'post', $url = '', $data = array(), $headers = array())
{
$options = $this->_options;
$res = ['status' => -1, 'res' => []];
try {
switch ($request_type) {
case 'post':
$response = Requests::post($url, $headers, $data, $options);
break;
case 'get':
$response = Requests::request($url, $headers, $data, Requests::GET, $options);
break;
default:
$response = Requests::post($url, $headers, $data, $options);
break;
}
if ($response->status_code == 200) {
$res = ['status' => 0, 'msg' => 'success', 'res' => trim($response->body)];
} else {
$res = ['status' => -1, 'msg' => 'fail', 'res' => trim($response->body)];
}
} catch (Exception $e) {
$res = ['status' => -1, 'msg' => $e->getMessage(), 'res' => ''];
}
return $res;
}
示例2: process_request
/**
* Process Netki API request and response
*
* @param string $partnerId
* @param string $apiKey
* @param string $apiURL
* @param string $method
* @param array $data
* @return array|mixed
* @throws \Exception
*/
public function process_request($partnerId, $apiKey, $apiURL, $method, $data)
{
$supportedMethods = array('GET', 'PUT', 'POST', 'DELETE');
$successCodes = array(200, 201, 202, 204);
if (!in_array($method, $supportedMethods)) {
throw new \Exception('Unsupported method: ' . $method);
}
$headers = array('content-type' => 'application/json', 'X-Partner-ID' => $partnerId, 'Authorization' => $apiKey);
$postData = !empty($data) ? json_encode($data) : null;
$response = \Requests::request($apiURL, $headers, $postData, $method);
if ($method == 'DELETE' && $response->status_code == 204) {
return array();
}
$responseData = json_decode($response->body);
if (empty($responseData)) {
throw new \Exception('Error parsing JSON Data');
}
if (!$responseData->success || !in_array($response->status_code, $successCodes)) {
$errorMessage = $responseData->message;
if (isset($responseData->failures)) {
$errorMessage .= ' [FAILURES: ';
$failures = array();
foreach ($responseData->failures as $failure) {
array_push($failures, $failure->message);
}
$errorMessage .= join(', ', $failures) . ']';
}
throw new \Exception('Request Failed: ' . $errorMessage);
}
return $responseData;
}
示例3: testGETWithDataAndQuery
public function testGETWithDataAndQuery()
{
$data = array('test2' => 'test');
$request = Requests::request('http://httpbin.org/get?test=true', array(), $data, Requests::GET, $this->getOptions());
$this->assertEquals(200, $request->status_code);
$result = json_decode($request->body, true);
$this->assertEquals('http://httpbin.org/get?test=true&test2=test', $result['url']);
$this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['args']);
}
示例4: request
public function request($method, $url, $data = null)
{
$url = Api::$baseUrl . $url;
if ($data === null) {
$data = array();
}
$options = array('auth' => array(Api::$key, Api::$secret));
$response = \Requests::request($url, self::$headers, $data, $method, $options);
$this->checkErrors($response);
return json_decode($response->body, true);
}
示例5: request
/**
* @inheritdoc
*/
public function request($url, $args, $method, Options $options)
{
$headers = $options->get('headers', array());
$method = Filter::up($method);
$args = 'GET' !== $method ? $args : array();
$httpResult = \Requests::request($url, $headers, $args, $method, $this->_getClientOptions($options));
if ($options->isExceptions() && $httpResult->status_code >= 400) {
throw new Exception($httpResult->body, $httpResult->status_code);
}
return array($httpResult->status_code, $httpResult->headers->getAll(), $httpResult->body);
}
示例6: load
/**
* @inheritDoc
*/
public function load(IApiRequest $request)
{
$req = $request->getRequestDetail();
try {
$response = \Requests::request($req->getUrl(), $this->_buildHeaders($req), $this->_buildData($req), $req->getMethod(), $req->getOptions());
$result = $this->_getResult($response);
$request->setRawResult($result);
return $request;
} catch (\Exception $e) {
$this->_handleException($e);
}
}
示例7: send
/**
* Send a request
*
* @param string $url
* @param string $method
* @param array $data
* @param array $headers
* @param array $options
*/
public function send($url, $method = self::GET, $data = array(), $headers = array(), $options = array())
{
if (isset($this->_auth)) {
$options['auth'] = $this->_auth;
}
try {
$response = \Requests::request($url, $headers, $data, $method, $options);
return new Response($response);
} catch (Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
}
示例8: testInvalidProtocol
/**
* @expectedException Requests_Exception
*/
public function testInvalidProtocol()
{
$request = Requests::request('ftp://128.0.0.1/');
}
示例9: request
/**
* Main interface for HTTP requests
*
* This method initiates a request and sends it via a transport before
* parsing.
*
* @see Requests::request()
*
* @throws Requests_Exception On invalid URLs (`nonhttp`)
*
* @param string $url URL to request
* @param array $headers Extra headers to send with the request
* @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
* @param string $type HTTP request type (use Requests constants)
* @param array $options Options for the request (see {@see Requests::request})
* @return Requests_Response
*/
public function request($url, $headers = array(), $data = array(), $type = Requests::GET, $options = array())
{
$request = $this->merge_request(compact('url', 'headers', 'data', 'options'));
return Requests::request($request['url'], $request['headers'], $request['data'], $type, $request['options']);
}
示例10: request
/**
* Send an HTTP request to a URI.
*
* Please note: The only URI that are supported in the HTTP Transport implementation
* are the HTTP and HTTPS protocols.
*
* @access public
* @since 2.7.0
*
* @param string $url The request URL.
* @param string|array $args {
* Optional. Array or string of HTTP request arguments.
*
* @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
* Some transports technically allow others, but should not be
* assumed. Default 'GET'.
* @type int $timeout How long the connection should stay open in seconds. Default 5.
* @type int $redirection Number of allowed redirects. Not supported by all transports
* Default 5.
* @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
* Default '1.0'.
* @type string $user-agent User-agent value sent.
* Default WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ).
* @type bool $reject_unsafe_urls Whether to pass URLs through wp_http_validate_url().
* Default false.
* @type bool $blocking Whether the calling code requires the result of the request.
* If set to false, the request will be sent to the remote server,
* and processing returned to the calling code immediately, the caller
* will know if the request succeeded or failed, but will not receive
* any response from the remote server. Default true.
* @type string|array $headers Array or string of headers to send with the request.
* Default empty array.
* @type array $cookies List of cookies to send with the request. Default empty array.
* @type string|array $body Body to send with the request. Default null.
* @type bool $compress Whether to compress the $body when sending the request.
* Default false.
* @type bool $decompress Whether to decompress a compressed response. If set to false and
* compressed content is returned in the response anyway, it will
* need to be separately decompressed. Default true.
* @type bool $sslverify Whether to verify SSL for the request. Default true.
* @type string sslcertificates Absolute path to an SSL certificate .crt file.
* Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
* @type bool $stream Whether to stream to a file. If set to true and no filename was
* given, it will be droped it in the WP temp dir and its name will
* be set using the basename of the URL. Default false.
* @type string $filename Filename of the file to write to when streaming. $stream must be
* set to true. Default null.
* @type int $limit_response_size Size in bytes to limit the response to. Default null.
*
* }
* @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
* A WP_Error instance upon error.
*/
public function request($url, $args = array())
{
$defaults = array('method' => 'GET', 'timeout' => apply_filters('http_request_timeout', 5), 'redirection' => apply_filters('http_request_redirection_count', 5), 'httpversion' => apply_filters('http_request_version', '1.0'), 'user-agent' => apply_filters('http_headers_useragent', 'WordPress/' . get_bloginfo('version') . '; ' . get_bloginfo('url')), 'reject_unsafe_urls' => apply_filters('http_request_reject_unsafe_urls', false), 'blocking' => true, 'headers' => array(), 'cookies' => array(), 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => true, 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt', 'stream' => false, 'filename' => null, 'limit_response_size' => null);
// Pre-parse for the HEAD checks.
$args = wp_parse_args($args);
// By default, Head requests do not cause redirections.
if (isset($args['method']) && 'HEAD' == $args['method']) {
$defaults['redirection'] = 0;
}
$r = wp_parse_args($args, $defaults);
/**
* Filters the arguments used in an HTTP request.
*
* @since 2.7.0
*
* @param array $r An array of HTTP request arguments.
* @param string $url The request URL.
*/
$r = apply_filters('http_request_args', $r, $url);
// The transports decrement this, store a copy of the original value for loop purposes.
if (!isset($r['_redirection'])) {
$r['_redirection'] = $r['redirection'];
}
/**
* Filters whether to preempt an HTTP request's return value.
*
* Returning a non-false value from the filter will short-circuit the HTTP request and return
* early with that value. A filter should return either:
*
* - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements
* - A WP_Error instance
* - boolean false (to avoid short-circuiting the response)
*
* Returning any other value may result in unexpected behaviour.
*
* @since 2.9.0
*
* @param false|array|WP_Error $preempt Whether to preempt an HTTP request's return value. Default false.
* @param array $r HTTP request arguments.
* @param string $url The request URL.
*/
$pre = apply_filters('pre_http_request', false, $r, $url);
if (false !== $pre) {
return $pre;
}
if (function_exists('wp_kses_bad_protocol')) {
if ($r['reject_unsafe_urls']) {
//.........这里部分代码省略.........
示例11: getRemoteResource
/**
* Return remote file's content via HTTP
*
* @param string $url The address of the target file
* @param string $body HTTP request body
* @param int $timeout Connection timeout
* @param string $method GET/POST
* @param string $content_type Content type header of HTTP request
* @param string[] $headers Headers key value array.
* @param string[] $cookies Cookies key value array.
* @param string $post_data Request arguments array for POST method
* @return string If success, the content of the target file. Otherwise: none
*/
public static function getRemoteResource($url, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array(), $cookies = array(), $post_data = array(), $request_config = array())
{
try {
$host = parse_url($url, PHP_URL_HOST);
$request_headers = array();
$request_cookies = array();
$request_options = array('timeout' => $timeout);
foreach ($headers as $key => $val) {
$request_headers[$key] = $val;
}
if (isset($cookies[$host]) && is_array($cookies[$host])) {
foreach ($cookies[$host] as $key => $val) {
$request_cookies[] = rawurlencode($key) . '=' . rawurlencode($val);
}
}
if (count($request_cookies)) {
$request_headers['Cookie'] = implode('; ', $request_cookies);
}
foreach ($request_config as $key => $val) {
$request_options[$key] = $val;
}
if ($content_type) {
$request_headers['Content-Type'] = $content_type;
}
if (defined('__PROXY_SERVER__')) {
$proxy = parse_url(__PROXY_SERVER__);
if ($proxy["host"]) {
$request_options['proxy'] = array($proxy['host'] . ($proxy['port'] ? ':' . $proxy['port'] : ''));
if ($proxy['user'] && $proxy['pass']) {
$request_options['proxy'][] = $proxy['user'];
$request_options['proxy'][] = $proxy['pass'];
}
}
}
$url = str_replace('&', '&', $url);
$start_time = microtime(true);
$response = Requests::request($url, $request_headers, $body ?: $post_data, $method, $request_options);
$elapsed_time = microtime(true) - $start_time;
$GLOBALS['__remote_request_elapsed__'] += $elapsed_time;
$log = array();
$log['url'] = $url;
$log['status'] = $response ? $response->status_code : 0;
$log['elapsed_time'] = $elapsed_time;
if (config('debug.enabled') && in_array('slow_remote_requests', config('debug.display_content'))) {
$bt = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
foreach ($bt as $no => $call) {
if (strncasecmp($call['function'], 'getRemote', 9) === 0) {
$call_no = $no + 1;
$log['called_file'] = $bt[$call_no]['file'];
$log['called_line'] = $bt[$call_no]['line'];
$call_no++;
$log['called_method'] = $bt[$call_no]['class'] . $bt[$call_no]['type'] . $bt[$call_no]['function'];
$log['backtrace'] = array_slice($bt, $call_no, 1);
break;
}
}
} else {
$log['called_file'] = $log['called_line'] = $log['called_method'] = null;
$log['backtrace'] = array();
}
Rhymix\Framework\Debug::addRemoteRequest($log);
if (count($response->cookies)) {
foreach ($response->cookies as $cookie) {
$cookies[$host][$cookie->name] = $cookie->value;
}
}
if ($response->success) {
if (isset($request_config['filename'])) {
return true;
} else {
return $response->body;
}
} else {
return NULL;
}
} catch (Exception $e) {
return NULL;
}
}
示例12: yourls_http_request
/**
* Perform a HTTP request, return response object
*
* @since 1.7
* @param string $type HTTP request type (GET, POST)
* @param string $url URL to request
* @param array $headers Extra headers to send with the request
* @param array $data Data to send either as a query string for GET requests, or in the body for POST requests
* @param array $options Options for the request (see /includes/Requests/Requests.php:request())
* @return object Requests_Response object
*/
function yourls_http_request($type, $url, $headers, $data, $options)
{
yourls_http_load_library();
$options = array_merge(yourls_http_default_options(), $options);
if (yourls_http_proxy_is_defined() && !yourls_send_through_proxy($url)) {
unset($options['proxy']);
}
try {
$result = Requests::request($url, $headers, $data, $type, $options);
} catch (Requests_Exception $e) {
$result = yourls_debug_log($e->getMessage() . ' (' . $type . ' on ' . $url . ')');
}
return $result;
}
示例13: testLOCKWithData
public function testLOCKWithData()
{
$data = array('test' => 'true', 'test2' => 'test');
$request = Requests::request(httpbin('/lock'), array(), $data, 'LOCK', $this->getOptions());
$this->assertEquals(200, $request->status_code);
$result = json_decode($request->body, true);
$this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']);
}
示例14: yourls_http_request
/**
* Perform a HTTP request, return response object
*
* @since 1.7
* @param string $type HTTP request type (GET, POST)
* @param string $url URL to request
* @param array $headers Extra headers to send with the request
* @param array $data Data to send either as a query string for GET requests, or in the body for POST requests
* @param array $options Options for the request (see /includes/Requests/Requests.php:request())
* @return object Requests_Response object
*/
function yourls_http_request($type, $url, $headers, $data, $options)
{
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter('shunt_yourls_http_request', null, $type, $url, $headers, $data, $options);
if (null !== $pre) {
return $pre;
}
yourls_http_load_library();
$options = array_merge(yourls_http_default_options(), $options);
if (yourls_http_get_proxy() && !yourls_send_through_proxy($url)) {
unset($options['proxy']);
}
try {
$result = Requests::request($url, $headers, $data, $type, $options);
} catch (Requests_Exception $e) {
$result = yourls_debug_log($e->getMessage() . ' (' . $type . ' on ' . $url . ')');
}
return $result;
}
示例15: http_request
/**
* Make a HTTP request to a remote URL
*
* @param string $method
* @param string $url
* @param array $headers
* @param array $options
* @return object
*/
function http_request($method, $url, $data = null, $headers = array(), $options = array())
{
$pem_copied = false;
// cURL can't read Phar archives
if (0 === strpos(WP_CLI_ROOT, 'phar://')) {
$options['verify'] = sys_get_temp_dir() . '/wp-cli-cacert.pem';
copy(WP_CLI_ROOT . '/vendor/rmccue/requests/library/Requests/Transport/cacert.pem', $options['verify']);
$pem_copied = true;
}
try {
$request = \Requests::request($url, $headers, $data, $method, $options);
if ($pem_copied) {
unlink($options['verify']);
}
return $request;
} catch (\Requests_Exception $ex) {
// Handle SSL certificate issues gracefully
\WP_CLI::warning($ex->getMessage());
if ($pem_copied) {
unlink($options['verify']);
}
$options['verify'] = false;
try {
return \Requests::request($url, $headers, $data, $method, $options);
} catch (\Requests_Exception $ex) {
\WP_CLI::error($ex->getMessage());
}
}
}