Http.php
1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
/**
 * Created by PhpStorm.
 * User: Hanson
 * Date: 2016/12/9
 * Time: 21:13
 */
namespace Hanson\Vbot\Core;
use GuzzleHttp\Client as HttpClient;
use Hanson\Vbot\Support\Console;
class Http
{
    static $instance;
    protected $client;
    /**
     * @return Http
     */
    public static function getInstance()
    {
        if(!static::$instance){
            static::$instance = new Http();
        }
        return static::$instance;
    }
    public function get($url, array $query = [], array $options = [])
    {
        if($query){
            $options['query'] = $query;
        }
        $options['connect_timeout'] = 60;
        return $this->request($url, 'GET', $options);
    }
    public function post($url, $query = [], $array = false)
    {
        $key = is_array($query) ? 'form_params' : 'body';
        $content = $this->request($url, 'POST', [$key => $query]);
        return $array ? json_decode($content, true) : $content;
    }
    public function json($url, $params = [], $array = false, $extra = [])
    {
        $params = array_merge(['json' => $params], $extra);
        $content = $this->request($url, 'POST', $params);
        return $array ? json_decode($content, true) : $content;
    }
    public function setClient(HttpClient $client)
    {
        $this->client = $client;
        return $this;
    }
    /**
     * Return GuzzleHttp\Client instance.
     *
     * @return \GuzzleHttp\Client
     */
    public function getClient()
    {
        if (!($this->client instanceof HttpClient)) {
            $this->client = new HttpClient(['cookies' => true]);
        }
        return $this->client;
    }
    /**
     * @param $url
     * @param string $method
     * @param array $options
     * @return string
     */
    public function request($url, $method = 'GET', $options = [])
    {
        $response = $this->getClient()->request($method, $url, $options);
        return $response->getBody()->getContents();
    }
}