Commit 3cee9214 authored by tufengqi's avatar tufengqi

新增通用的http 模块

parent 3346f850
<?php
namespace fpf\http;
use fpf\http\exception\CurlHttpException;
class CurlHttpClient
{
/**
* The URI to request
*
* @var string
*/
protected $full_url;
/**
* The scheme to use for the request, i.e. http, https
*
* @var string
*/
protected $scheme;
/**
* Buffer for the HTTP request data
*
* @var string
*/
protected $post_fields;
/**
* http headers
*
* @var array
*/
protected $headers;
protected $uri_no_func;
protected $connect_timeout_ms;
protected $timeout_ms;
protected $method;
protected $curl_handle;
protected $response;
const METHOD_POST = 'POST';
const METHOD_GET = 'GET';
public function __construct()
{
$config = \Yii::$app->fpf->loadConfig('http_options');
$this->connect_timeout_ms = $config['connect_timeout'] ?? 10;
$this->timeout_ms = $config['timeout_ms'] ?? 100;
}
/**
* Set read timeout
*
* @param float $timeout
*/
public function setTimeoutSecs($timeout)
{
$this->timeout = $timeout;
}
/**
* Close the transport.
*/
public function close()
{
$this->request = '';
$this->response = null;
}
public function get($url, $get_arr, $options = [])
{
$arr = explode(':', $url);
$scheme = 'https' === $arr[0] ? 'https' : 'http';
$this->scheme = $scheme;
$this->full_url = $url . '?' . http_build_query($get_arr);
if ($options['time']['connect_timeout_ms']) {
$this->connect_timeout_ms = $options['time']['connect_timeout'];
}
if ($options['time']['timeout_ms']) {
$this->timeout_ms = $options['time']['timeout_ms'];
}
if ($options['headers']) {
$this->headers = $options['headers'];
}
if ($options['cookies']) {
$this->cookies = $options['cookies'];
}
$this->method = self::METHOD_GET;
$this->flush();
return $this->response;
}
public function post($url, $post_arr, $options = [])
{
$arr = explode(':', $url);
$scheme = 'https' === $arr[0] ? 'https' : 'http';
$this->scheme = $scheme;
$this->full_url = $url;
$this->post_arr = $post_arr;
if ($options['time']['connect_timeout_ms']) {
$this->connect_timeout_ms = $options['time']['connect_timeout'];
}
if ($options['time']['timeout_ms']) {
$this->timeout_ms = $options['time']['timeout_ms'];
}
if ($options['headers']) {
$this->headers = $options['headers'];
}
if ($options['cookies']) {
$this->cookies = $options['cookies'];
}
$this->method = self::METHOD_POST;
$this->flush();
return $this->response;
}
/**
* @param string $method
* @param array $params
* @param array $cookies
* @throws CurlHttpException
*/
public function flush()
{
register_shutdown_function([$this, 'closeCurlHandle']);
$this->curl_handle = curl_init();
curl_setopt($this->curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl_handle, CURLOPT_BINARYTRANSFER, true);
curl_setopt($this->curl_handle, CURLOPT_USERAGENT, 'PHP/TCurlClient');
if (self::METHOD_POST === $this->method) {
curl_setopt($this->curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');
}
curl_setopt($this->curl_handle, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->curl_handle, CURLOPT_MAXREDIRS, 1);
$cookie_set = false;
$cookie_string = '';
if (defined('SERVICE_FORCE_VERSION_KEY') && !empty($GLOBALS['GLOBAL_VERSION_VALUE_NO_PTEFIX'])) {
$cookie_string .= SERVICE_FORCE_VERSION_KEY . '=' . $GLOBALS['GLOBAL_VERSION_VALUE_NO_PTEFIX'] . ';';
$cookie_set = true;
} elseif (!empty($cookies)) {
$cookie_set = true;
}
if (true === $cookie_set) {
foreach ($cookies as $key => $value) {
$cookie_string .= $key . '=' . $value . ';';
}
curl_setopt($this->curl_handle, CURLOPT_COOKIE, $cookie_string);
}
// God, PHP really has some esoteric ways of doing simple things.
$full_url = $this->full_url;
$headers = [];
foreach ($this->headers as $key => $value) {
$headers[] = "$key: $value";
}
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($this->curl_handle, CURLOPT_TIMEOUT_MS, $this->timeout_ms);
curl_setopt($this->curl_handle, CURLOPT_CONNECTTIMEOUT_MS, $this->connect_timeout_ms);
if (self::METHOD_POST === $this->method) {
curl_setopt($this->curl_handle, CURLOPT_POSTFIELDS, $this->post_fields);
}
$this->post_fields = '';
curl_setopt($this->curl_handle, CURLOPT_URL, $full_url);
$this->response = curl_exec($this->curl_handle);
// Connect failed?
if (!$this->response) {
curl_close($this->curl_handle);
$this->curl_handle = null;
$error = 'CurlHttpClient: Could not connect to ' . $full_url;
throw new CurlHttpException($error, CurlHttpException::NOT_OPEN);
}
}
public function closeCurlHandle()
{
try {
if ($this->curl_handle) {
curl_close($this->curl_handle);
$this->curl_handle = null;
}
} catch (\Exception $x) {
error_log('There was an error closing the curl handle: ' . $x->getMessage());
}
}
public function addHeaders($headers)
{
$this->headers = array_merge($this->headers, $headers);
}
}
<?php
namespace fpf\http;
use fpf\http\CurlHttpClient;
use fpf\http\SwoftHttpClient;
class FpfHttpClient
{
/**
* @var $http_client CurlHttpClient|SwoftHttpClient
*/
private $http_client;
public function __construct()
{
if (defined('IS_SWOOLE_SERVICE') && IS_SWOOLE_SERVICE === true) {
$this->http_client = new SwoftHttpClient();
} else {
$this->http_client = new CurlHttpClient();
}
}
public function get($url, $get_arr, $options = [])
{
return $this->http_client->get($url, $get_arr, $options);
}
public function post($url, $post_arr, $options = [])
{
return $this->http_client->post($url, $post_arr, $options);
}
}
<?php
namespace fpf\http;
use fpf\http\exception\SwoftHttpException;
use Swoft\HttpClient\Client;
class SwoftHttpClient
{
/**
* The URI to request
*
* @var string
*/
protected $full_url;
/**
* The scheme to use for the request, i.e. http, https
*
* @var string
*/
protected $scheme;
/**
* Buffer for the HTTP request data
*
* @var string
*/
protected $post_fields;
/**
* http headers
*
* @var array
*/
protected $headers;
protected $uri_no_func;
protected $connect_timeout_ms;
protected $timeout_ms;
protected $method;
protected $curl_handle;
protected $response;
const METHOD_POST = 'POST';
const METHOD_GET = 'GET';
public function __construct()
{
$config = \Yii::$app->fpf->loadConfig('http_options');
$this->connect_timeout_ms = $config['connect_timeout'] ?? 10;
$this->timeout_ms = $config['timeout_ms'] ?? 100;
}
/**
* Set read timeout
*
* @param float $timeout
*/
public function setTimeoutSecs($timeout)
{
$this->timeout = $timeout;
}
/**
* Close the transport.
*/
public function close()
{
$this->request = '';
$this->response = null;
}
public function get($url, $get_arr, $options = [])
{
$arr = explode(':', $url);
$scheme = 'https' === $arr[0] ? 'https' : 'http';
$this->scheme = $scheme;
$this->full_url = $url . '?' . http_build_query($get_arr);
if ($options['time']['connect_timeout_ms']) {
$this->connect_timeout_ms = $options['time']['connect_timeout'];
}
if ($options['time']['timeout_ms']) {
$this->timeout_ms = $options['time']['timeout_ms'];
}
if ($options['headers']) {
$this->headers = $options['headers'];
}
if ($options['cookies']) {
$this->cookies = $options['cookies'];
}
$this->method = self::METHOD_GET;
$this->flush();
return $this->response;
}
public function post($url, $post_arr, $options = [])
{
$arr = explode(':', $url);
$scheme = 'https' === $arr[0] ? 'https' : 'http';
$this->scheme = $scheme;
$this->full_url = $url;
$this->post_arr = $post_arr;
if ($options['time']['connect_timeout_ms']) {
$this->connect_timeout_ms = $options['time']['connect_timeout'];
}
if ($options['time']['timeout_ms']) {
$this->timeout_ms = $options['time']['timeout_ms'];
}
if ($options['headers']) {
$this->headers = $options['headers'];
}
if ($options['cookies']) {
$this->cookies = $options['cookies'];
}
$this->method = self::METHOD_POST;
$this->flush();
return $this->response;
}
/**
* @throws SwoftHttpException
*/
public function flush()
{
register_shutdown_function([$this, 'closeCurlHandle']);
$this->curl_handle = new Client(['adapter' => 'co']);//使用协程驱动
$full_url = $this->full_url;
$headers = [];
foreach ($this->headers as $key => $value) {
$headers[] = "$key: $value";
}
if (defined('VERSION_KEY') && defined('VERSION_VALUE_NO_PTEFIX')) {
$options['headers'][VERSION_KEY] = VERSION_VALUE_NO_PTEFIX;
}
if (self::METHOD_POST === $this->method) {
$options['body'] = $this->request_;
}
$options['timeout'] = $this->timeout_ms / 1000;
$this->post_fields = '';
$this->response = $this->curl_handle->request('POST', $full_url, $options)->getResult();
// Connect failed?
if (!$this->response) {
$this->curl_handle = null;
$error = 'CurlHttpClient: Could not connect to ' . $full_url;
throw new SwoftHttpException($error, SwoftHttpException::NOT_OPEN);
}
}
public function closeCurlHandle()
{
try {
if ($this->curl_handle) {
curl_close($this->curl_handle);
$this->curl_handle = null;
}
} catch (\Exception $x) {
error_log('There was an error closing the curl handle: ' . $x->getMessage());
}
}
public function addHeaders($headers)
{
$this->headers = array_merge($this->headers, $headers);
}
}
<?php
namespace fpf\http\exception;
class CurlHttpException extends \Exception
{
const NOT_OPEN = 4000;
public function __construct($message, $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
<?php
namespace fpf\http\exception;
class SwoftHttpException extends \Exception
{
const NOT_OPEN = 4000;
public function __construct($message, $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
......@@ -79,7 +79,7 @@ class ThriftServiceFactoryProxy
goto doEnd;
}
doEnd :
if ($error) {
if ($error) {
return ResponseApi::arrFail($error);
}
return ResponseApi::arrSuccess([$tem_arr[1], $matches[1]]);
......@@ -93,7 +93,7 @@ class ThriftServiceFactoryProxy
$this->request_base_params['port'],
$this->request_base_params['uri'],
'http',
$service_real
$this->service_real_config
);
$socket->addHeaders(['Contents-Type' => $this->request_base_params['content_type_str']]);
} else {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment