Files
kiri-wchat/common/HttpClient.php
T

703 lines
13 KiB
PHP
Raw Normal View History

2018-07-19 12:10:22 +08:00
<?php
2019-11-11 18:14:47 +08:00
namespace common;
2018-07-19 12:10:22 +08:00
2019-12-02 17:07:04 +08:00
use Swoole\Coroutine\Http\Client as SClient;
2019-09-29 17:10:14 +08:00
use Swoole\Coroutine\System;
2019-05-21 16:01:42 +08:00
2019-11-11 18:14:47 +08:00
class HttpClient
2018-07-19 12:10:22 +08:00
{
2019-07-17 17:17:37 +08:00
private $host = 'api.weixin.qq.com';
2018-07-19 12:10:22 +08:00
2019-07-12 18:44:54 +08:00
private $header = [];
2018-07-19 12:10:22 +08:00
2019-07-17 17:17:37 +08:00
private $callback = null;
private $method = 'get';
private $url = '';
private $isSSL = false;
2019-09-19 18:34:06 +08:00
private $agent = '';
2019-11-11 18:14:47 +08:00
private $isFileStream = false;
private $errorCodeField = '';
private $errorMsgField = '';
2019-12-02 17:07:04 +08:00
private $use_swoole = false;
private $ssl_cert_file = '';
private $ssl_key_file = '';
2019-07-17 17:17:37 +08:00
2019-12-18 20:08:51 +08:00
private $port = 80;
2019-12-19 15:57:51 +08:00
private $_data = '';
2019-07-17 17:17:37 +08:00
const POST = 'post';
const GET = 'get';
const PUT = 'put';
const DELETE = 'delete';
const OPTIONS = 'option';
2019-11-11 18:14:47 +08:00
/**
* HttpClient constructor.
*/
2019-09-19 19:04:43 +08:00
private function __construct()
{
}
2019-12-19 15:57:51 +08:00
public function setData($data)
{
$this->_data = $data;
}
2019-09-19 19:04:43 +08:00
/**
2019-12-02 17:07:04 +08:00
* @return string
*/
public function getSslCertFile(): string
{
return $this->ssl_cert_file;
}
/**
* @param string $ssl_cert_file
*/
public function setSslCertFile(string $ssl_cert_file)
{
$this->ssl_cert_file = $ssl_cert_file;
}
/**
* @return string
*/
public function getSslKeyFile(): string
{
return $this->ssl_key_file;
}
/**
* @param string $ssl_key_file
*/
public function setSslKeyFile(string $ssl_key_file)
{
$this->ssl_key_file = $ssl_key_file;
}
/**
2019-09-19 19:04:43 +08:00
*/
2019-11-11 18:14:47 +08:00
public static function NewRequest()
2019-09-19 19:04:43 +08:00
{
2019-10-18 10:40:38 +08:00
static $client = null;
2019-11-11 18:14:47 +08:00
if (!($client instanceof HttpClient)) {
$client = new HttpClient();
2019-09-19 19:04:43 +08:00
}
2019-10-18 10:40:38 +08:00
return $client;
2019-09-19 19:04:43 +08:00
}
2019-11-11 18:14:47 +08:00
/**
* @param string $name
* @return $this
*/
public function setErrorField(string $name)
{
$this->errorCodeField = $name;
return $this;
}
2019-12-02 17:07:04 +08:00
/**
* @param $bool
* @return $this
*/
public function setUseSwoole($bool)
{
$this->use_swoole = $bool;
return $this;
}
2019-11-11 18:14:47 +08:00
/**
* @param string $name
* @return $this
*/
public function setErrorMsgField(string $name)
{
$this->errorMsgField = $name;
return $this;
}
2019-07-17 17:17:37 +08:00
/**
* @param string $host
*/
public function setHost(string $host)
{
$this->host = $host;
}
/**
* @param array $header
*/
public function setHeader(array $header)
{
$this->header = $header;
}
/**
* @param $key
* @param $value
*/
public function addHeader($key, $value)
{
$this->header[$key] = $value;
}
/**
* @param null $callback
*/
public function setCallback($callback)
{
$this->callback = $callback;
}
/**
* @param string $method
*/
public function setMethod(string $method)
{
$this->method = $method;
}
/**
* @param string $url
*/
public function setUrl(string $url)
{
$this->url = $url;
}
2019-09-19 18:34:06 +08:00
public function setAgent(string $agent)
{
$this->agent = $agent;
}
2019-07-17 17:17:37 +08:00
/**
* @param bool $isSSL
*/
public function setIsSSL(bool $isSSL)
{
$this->isSSL = $isSSL;
2019-12-19 10:53:19 +08:00
if ($this->isSSL) {
$this->port = 443;
}
2019-12-18 20:08:51 +08:00
}
public function setPort($port)
{
$this->port = $port;
2019-11-04 14:39:59 +08:00
}
2019-11-11 18:14:47 +08:00
/**
* @return bool
*/
2019-11-04 14:39:59 +08:00
public function getIsSSL()
{
return $this->isSSL;
2019-07-17 17:17:37 +08:00
}
2019-11-11 18:14:47 +08:00
/**
* @param bool $isFIle
* 设置返回类型
*/
public function asFileStream($isFIle = true)
{
$this->isFileStream = $isFIle;
}
2019-07-17 17:17:37 +08:00
2019-07-12 18:44:54 +08:00
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
2019-07-17 17:17:37 +08:00
private function request($url, $data = [])
2019-07-12 18:44:54 +08:00
{
2019-11-11 18:14:47 +08:00
$data = $this->paramEncode($data);
2019-12-02 17:07:04 +08:00
if ($this->use_swoole === false) {
return $this->useCurl($url, $data);
}
2019-09-29 17:10:14 +08:00
if (function_exists('getIsCli') && getIsCli()) {
2019-11-11 18:14:47 +08:00
return $this->coroutine($this->parseUrlHost($url), $url, $data);
2019-09-29 17:10:14 +08:00
}
2019-12-02 17:07:04 +08:00
return $this->useCurl($url, $data);
}
/**
* @param $url
* @param $data
* @return array|Result|mixed
*/
private function useCurl($url, $data)
{
2019-11-11 18:14:47 +08:00
if ($this->isHttp($url) || $this->isHttps($url)) {
2019-07-17 17:17:37 +08:00
return $this->curl($url, $data);
2019-07-12 18:44:54 +08:00
}
2019-07-17 17:17:37 +08:00
if ($this->isSSL) {
return $this->curl('https://' . $this->host . '/' . $url, $data);
} else {
return $this->curl('http://' . $this->host . '/' . $url, $data);
}
2019-07-12 18:44:54 +08:00
}
2018-07-19 12:10:22 +08:00
2019-11-11 18:14:47 +08:00
/**
* @param $url
* @return string
*/
private function parseUrlHost(&$url)
{
2019-12-19 10:51:57 +08:00
if (!empty($this->host)) {
return $this->host;
}
2019-11-11 18:14:47 +08:00
if ($this->isHttp($url)) {
$url = str_replace('http://', '', $url);
} else if ($this->isHttps($url)) {
$url = str_replace('https://', '', $url);
}
$explode = explode('/', $url);
2019-12-18 20:02:47 +08:00
$first = array_shift($explode);
2019-12-19 10:41:42 +08:00
if (strpos($first, ':') !== false) {
[$first, $this->port] = explode(':', $first);
if ($this->port !== 443) {
$this->isSSL = false;
2019-12-18 20:08:51 +08:00
}
2019-12-19 10:51:57 +08:00
$url = '/' . implode('/', $explode);
2019-12-19 10:41:42 +08:00
}
if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $first)) {
2019-12-18 20:02:47 +08:00
return $first;
}
return System::gethostbyname($first);
2019-11-11 18:14:47 +08:00
}
/**
* @param $url
* @return bool
*/
private function isHttp($url)
{
return strpos($url, 'http://') === 0;
}
/**
* @param $url
* @return bool
*/
private function isHttps($url)
{
return strpos($url, 'https://') === 0;
}
2019-07-12 18:44:54 +08:00
/**
2019-09-29 17:10:14 +08:00
* @param $ip
2019-07-12 18:50:05 +08:00
* @param $url
2019-07-12 18:44:54 +08:00
* @param array $data
2019-07-12 18:50:05 +08:00
* @return array|mixed|Result
* @throws \Exception
2019-07-12 18:44:54 +08:00
* 使用swoole协程方式请求
*/
2019-09-29 17:10:14 +08:00
private function coroutine($ip, $url, $data = [])
2019-07-12 18:44:54 +08:00
{
2019-11-11 18:14:47 +08:00
$client = $this->generate_client($ip, $url, $data);
2019-07-17 17:17:37 +08:00
if ($client->statusCode < 0) {
2019-08-21 13:20:56 +08:00
throw new \Exception($client->errMsg);
2019-07-17 17:17:37 +08:00
}
2019-11-11 18:14:47 +08:00
2019-07-17 17:17:37 +08:00
$body = $client->body;
$client->close();
2019-12-02 17:07:04 +08:00
$header = $client->getHeaders();
$body = $this->resolve($header, $body);
if ($client->getStatusCode() != 200) {
return new Result(['code' => $client->getStatusCode(), 'message' => $body, 'header' => $header]);
}
return $this->structure($body, $data, $header);
2019-07-17 17:17:37 +08:00
}
2019-05-21 16:01:42 +08:00
2019-07-17 17:17:37 +08:00
/**
* @return mixed
*/
private function getHostIp()
{
2019-08-21 12:13:02 +08:00
$host = \Co::getAddrInfo($this->host);
return array_shift($host);
2019-07-17 17:17:37 +08:00
}
2019-05-21 16:01:42 +08:00
2019-07-17 17:17:37 +08:00
/**
* @return int
*/
private function getHostPort()
{
2019-12-18 20:08:51 +08:00
if (!empty($this->port)) {
return $this->port;
}
2019-07-17 17:17:37 +08:00
$port = 80;
if ($this->isSSL) $port = 443;
return $port;
}
/**
2019-09-29 17:10:14 +08:00
* @param $host
2019-07-17 17:17:37 +08:00
* @param $port
* @param $url
* @param $data
2019-12-02 17:07:04 +08:00
* @return \Swoole\Coroutine\Http\Client
2019-07-17 17:17:37 +08:00
*/
2019-11-11 18:14:47 +08:00
private function generate_client($host, $url, $data)
2019-07-17 17:17:37 +08:00
{
2019-12-02 17:07:04 +08:00
$client = new SClient($host, $this->getHostPort(), $this->isSSL);
2019-09-19 18:34:06 +08:00
if (!empty($this->agent)) {
$this->header['User-Agent'] = $this->agent;
}
2019-07-12 18:44:54 +08:00
if (!empty($this->header)) {
2019-12-02 17:07:04 +08:00
$client->setHeaders($this->parseHeaderMat());
2019-07-12 18:44:54 +08:00
}
2019-12-02 17:07:04 +08:00
2019-11-11 18:14:47 +08:00
if (strtolower($this->method) == self::GET) {
2019-12-19 15:57:51 +08:00
if (!empty($this->_data)) {
$client->setData($this->_data);
}
2019-11-11 18:14:47 +08:00
$client->get($url . '?' . $data);
2019-12-18 19:58:00 +08:00
} else if (strtolower($this->method) == self::PUT) {
2019-12-19 10:55:15 +08:00
$client->setMethod('PUT');
2019-12-19 12:17:56 +08:00
if (!is_string($data)) {
$data = json_encode($data, JSON_UNESCAPED_UNICODE);
}
$client->setData($data);
$client->execute($url);
} else if (strtolower($this->method) == self::DELETE) {
$client->setMethod('DELETE');
2019-12-18 19:58:00 +08:00
if (!is_string($data)) {
$data = json_encode($data, JSON_UNESCAPED_UNICODE);
}
$client->setData($data);
2019-12-19 10:56:14 +08:00
$client->execute($url);
2019-11-11 18:14:47 +08:00
} else {
$client->post($url, $data);
2019-07-12 18:44:54 +08:00
}
2019-07-17 17:17:37 +08:00
return $client;
2019-07-12 18:44:54 +08:00
}
2019-05-21 16:01:42 +08:00
2019-07-12 18:44:54 +08:00
/**
* @param $url
* @param array $data
* @return array|mixed|Result
*/
2019-07-17 17:17:37 +08:00
private function curl($url, $data = [])
2019-07-12 18:44:54 +08:00
{
2019-12-02 17:07:04 +08:00
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->createRequestUrl($url, $data));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);// 超时设置
curl_setopt($ch, CURLOPT_HEADER, true);
if ($headers = $this->parseHeaderMat()) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if (!empty($this->agent)) {
curl_setopt($ch, CURLOPT_USERAGENT, $this->agent);
}
curl_setopt($ch, CURLOPT_SSLCERT, $this->getSslCertFile());
curl_setopt($ch, CURLOPT_SSLKEY, $this->getSslKeyFile());
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); // 超时设置
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);//返回内容
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);// 跟踪重定向
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
if ($this->method == self::POST) {
curl_setopt($ch, CURLOPT_POST, 1);
}
if ($this->method != self::GET) {
2019-12-25 16:32:54 +08:00
if (!empty($this->_data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_data);
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
2019-12-02 17:07:04 +08:00
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($this->method));
$output = curl_exec($ch);
curl_close($ch);
if ($output === FALSE) {
2020-01-07 11:57:56 +08:00
$data = new Result(['code' => 500, 'message' => curl_error($ch)]);
} else {
[$header, $body, $status] = $this->explode($output);
2020-01-03 15:06:08 +08:00
2020-01-07 11:57:56 +08:00
if ($status != 200) {
$data = new Result(['code' => 500, 'message' => $body, 'header' => $header]);
} else {
$data = $this->structure($body, $data, $header);
}
2019-12-02 17:07:04 +08:00
}
2020-01-07 11:57:56 +08:00
unset($ch);
return $data;
2019-12-02 17:07:04 +08:00
} catch (\Exception $exception) {
return new Result(['code' => 500, 'message' => $exception->getMessage(), 'header' => []]);
2019-11-11 18:14:47 +08:00
}
2019-07-12 18:44:54 +08:00
}
2019-05-21 16:01:42 +08:00
2020-01-03 15:12:06 +08:00
/**
* @param $output
* @return array
*/
private function explode($output)
{
2020-01-03 15:35:28 +08:00
[$header, $body] = explode("\r\n\r\n", $output, 2);
2020-01-03 15:38:45 +08:00
if ($header == 'HTTP/1.1 100 Continue') {
[$header, $body] = explode("\r\n\r\n", $body, 2);
} else if (strpos($body, "\r\n\r\n") !== false) {
2020-01-03 15:36:18 +08:00
[$header, $body] = explode("\r\n\r\n", $body, 2);
}
2020-01-03 15:32:26 +08:00
$header = explode("\r\n", $header);
2020-01-03 15:12:06 +08:00
unset($output);
$status = (int)explode(' ', trim($header[0]))[1];
$header = $this->headerFormat($header);
return [$header, $this->resolve($header, $body), $status];
}
2019-07-12 18:44:54 +08:00
/**
* @param $url
2019-11-11 18:14:47 +08:00
* @param $data
* @return string
2019-07-12 18:44:54 +08:00
*/
2019-11-11 18:14:47 +08:00
private function createRequestUrl($url, $data)
2019-07-12 18:44:54 +08:00
{
2019-11-11 18:14:47 +08:00
if ($this->isGet()) {
return $url . '?' . $data;
2019-07-17 17:17:37 +08:00
}
2019-11-11 18:14:47 +08:00
return $url;
}
/**
* @param $data
* @param $body
* @return mixed
*/
private function resolve($data, $body)
{
2020-01-03 11:43:20 +08:00
if (is_array($body)) {
return $body;
}
2020-01-03 15:15:00 +08:00
$type = $data['content-type'];
2020-01-03 11:55:14 +08:00
if (strpos($type, 'text/html') !== false) {
2019-11-11 18:14:47 +08:00
return $body;
2020-01-03 11:55:14 +08:00
} else if (strpos($type, 'json') !== false) {
return Help::toArray($body);
} else if (strpos($type, 'xml') !== false) {
return Help::toArray($body);
} else if (strpos($type, 'plain') !== false) {
return Help::toArray($body);
2019-09-19 18:34:06 +08:00
}
2020-01-03 11:55:14 +08:00
return $body;
2019-11-11 18:14:47 +08:00
}
/**
* @param $headers
* @return array
*/
private function headerFormat($headers)
{
$_tmp = [];
foreach ($headers as $key => $val) {
$trim = explode(': ', trim($val));
2020-01-03 15:15:00 +08:00
$_tmp[strtolower($trim[0])] = $trim[1] ?? '';
2019-07-12 18:44:54 +08:00
}
2019-11-11 18:14:47 +08:00
return $_tmp;
2019-07-12 18:44:54 +08:00
}
2018-07-19 12:10:22 +08:00
2019-07-17 17:17:37 +08:00
/**
* @param $body
* @param $_data
2019-11-11 18:14:47 +08:00
* @param $header
2019-12-02 17:07:04 +08:00
* @param $statusCode
2019-07-17 17:17:37 +08:00
* @return array|mixed|Result
* 构建返回体
*/
2019-12-02 17:07:04 +08:00
private function structure($body, $_data, $header = [], $statusCode = 200)
2019-07-12 18:44:54 +08:00
{
2019-07-17 17:17:37 +08:00
$this->setIsSSL(false);
2019-08-21 13:27:12 +08:00
$this->setHeaders([]);
2019-07-17 17:17:37 +08:00
if ($this->callback !== NULL) {
2019-11-11 18:14:47 +08:00
$result = call_user_func($this->callback, $body, $_data, $header);
$this->setCallback(null);
2019-07-17 17:17:37 +08:00
return $result;
}
2019-11-11 18:14:47 +08:00
if (!is_array($body)) {
return $body;
}
2019-07-17 17:17:37 +08:00
2019-11-11 18:14:47 +08:00
$result['code'] = $body[$this->errorCodeField] ?? 0;
$result['message'] = $body[$this->errorMsgField] ?? 'system success.';
$result['data'] = $body;
$result['header'] = $header;
2019-12-02 17:07:04 +08:00
$result['httpStatus'] = $statusCode;
2019-07-17 17:17:37 +08:00
return new Result($result);
}
/**
2019-11-11 18:14:47 +08:00
* @return bool
* check isPost Request
2019-07-17 17:17:37 +08:00
*/
2019-11-11 18:14:47 +08:00
public function isPost()
2019-07-17 17:17:37 +08:00
{
2019-11-11 18:14:47 +08:00
return strtolower($this->method) === self::POST;
}
/**
* @return bool
*
* check isGet Request
*/
public function isGet()
{
return strtolower($this->method) === self::GET;
2019-07-12 18:44:54 +08:00
}
2018-07-19 12:10:22 +08:00
2019-07-12 18:44:54 +08:00
/**
* @param $arr
*
* @return array|string
* 将请求参数进行编码
*/
2019-11-11 18:14:47 +08:00
private function paramEncode($arr)
2019-07-12 18:44:54 +08:00
{
if (!is_array($arr)) {
return $arr;
}
$_tmp = [];
foreach ($arr as $Key => $val) {
$_tmp[$Key] = $val;
}
2019-11-11 18:14:47 +08:00
if ($this->isGet()) {
return http_build_query($_tmp);
}
return $_tmp;
2019-07-12 18:44:54 +08:00
}
2018-07-19 12:10:22 +08:00
2019-07-12 18:44:54 +08:00
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws
*/
2019-07-17 17:17:37 +08:00
public function post($url, $data = [])
2019-07-12 18:44:54 +08:00
{
2019-07-17 17:17:37 +08:00
$this->setMethod(self::POST);
return $this->request($url, $data);
2019-07-12 18:44:54 +08:00
}
2019-05-21 16:01:42 +08:00
2019-07-12 18:44:54 +08:00
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws
*/
2019-07-17 17:17:37 +08:00
public function put($url, $data = [])
2019-07-12 18:44:54 +08:00
{
2019-07-17 17:17:37 +08:00
$this->setMethod(self::PUT);
return $this->request($url, $data);
2019-07-12 18:44:54 +08:00
}
2018-07-19 12:10:22 +08:00
2019-07-12 18:44:54 +08:00
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws
*/
2019-07-17 17:17:37 +08:00
public function get($url, $data = [])
2019-07-12 18:44:54 +08:00
{
2019-07-17 17:17:37 +08:00
$this->setMethod(self::GET);
return $this->request($url, $data);
2019-07-12 18:44:54 +08:00
}
2018-07-19 12:10:22 +08:00
2019-07-12 18:44:54 +08:00
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
2019-07-17 17:17:37 +08:00
public function option($url, $data = [])
2019-07-12 18:44:54 +08:00
{
2019-07-17 17:17:37 +08:00
$this->setMethod(self::OPTIONS);
return $this->request($url, $data);
}
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
public function delete($url, $data = [])
{
$this->setMethod(self::DELETE);
return $this->request($url, $data);
2019-07-12 18:44:54 +08:00
}
2018-07-19 12:10:22 +08:00
2019-07-12 18:44:54 +08:00
/**
* @param $url
* @param array $data
* @return array|mixed|Result
* @throws \Exception
*/
2019-07-17 17:17:37 +08:00
public function send($url, $data = [])
2019-07-12 18:44:54 +08:00
{
2019-07-17 17:17:37 +08:00
return $this->request($url, $data);
2019-07-12 18:44:54 +08:00
}
2019-12-02 17:07:04 +08:00
/**
* @return array
*/
private function parseHeaderMat()
{
if ($this->use_swoole) {
return $this->header;
}
$headers = [];
foreach ($this->header as $key => $val) {
$header = $key . ':' . $val;
if (in_array($header, $headers)) {
continue;
}
$headers[] = $header;
}
$this->header = [];
return $headers;
}
2019-07-12 18:44:54 +08:00
/**
* @param array $headers
* @return array
*/
public function setHeaders(array $headers)
{
if (empty($headers)) {
return [];
}
foreach ($headers as $key => $val) {
2019-12-02 17:07:04 +08:00
$header = $key . ':' . $val;
if (in_array($header, $this->header)) {
continue;
}
$this->header[] = $header;
2019-07-12 18:44:54 +08:00
}
return $this->header;
}
2018-07-19 12:10:22 +08:00
}