123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163 |
- <?php
- namespace App\Library\HttpRequest;
- class Client
- {
-
- const GET = 'GET';
-
- const POST = 'POST';
- private function __construct()
- {
- }
-
- public static function get(string $url, array $headers = [], array $options = [])
- {
- return self::request($url,self::GET,$headers,[],$options);
- }
-
- public static function post(string $url, array $headers = [], array $data = [], array $options = [])
- {
- return self::request($url,self::POST,$headers,$data,$options);
- }
-
- private static function request(string $url, string $method, array $headers = [], array $data = [], array $options = [])
- {
- $url_info = parse_url($url);
- $domain = $url_info['host'];
- $is_https = strtolower($url_info['scheme']) == 'https';
- $port = $is_https ? 443 : 80;
- $client = new \Swoole\Coroutine\Http\Client($url_info['host'], $port, $is_https);
- $sets = [];
- $sets['timeout'] = isset($options['timeout']) ? intval($options['timeout']) : -1;
-
- if($is_https){
- $sets['ssl_host_name'] = $domain;
- }
- $content_type = '';
- if($headers){
- foreach ($headers as $key=>$val){
- $tempKey = strtolower($key);
- if($tempKey == 'content-type'){
- $content_type = $val;
- }
- }
- }
- $client->set($sets);
- $client->setHeaders($headers);
-
- if(isset($options['cookies'])){
- $client->setCookies($options['cookies']);
- }
-
- $path = isset($url_info['path']) ? strval($url_info['path']) : '';
- if(isset($url_info['query'])){
- $path .= '?'.$url_info['query'];
- }
- if(isset($url_info['fragment'])){
- $path .= '#'.$url_info['fragment'];
- }
- if($method == self::GET){
- $client->get($path);
- }elseif ($method == self::POST){
- $postContent = $data;
-
- if(stripos($content_type,'json') !== false){
- $postContent = json_encode($data);
- }
- $client->post($path,$postContent);
- }
- $response = new Response([
- 'errCode'=>$client->errCode,
- 'errMsg'=>$client->errMsg,
- 'body'=>strval($client->getBody()),
- 'statusCode'=>intval($client->getStatusCode()),
- 'cookies'=>$client->getCookies(),
- 'headers'=>$client->getHeaders(),
- ]);
-
-
-
-
-
-
-
-
- $client->close();
- return $response;
- }
- }
|