Http.php
1.36 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
<?php
/**
* Created by PhpStorm.
* User: Hanson
* Date: 2016/12/9
* Time: 21:13
*/
namespace Hanson\Robot\Core;
use GuzzleHttp\Client as HttpClient;
class Http
{
protected $client;
public function get($url, array $options = [])
{
$query = $options ? ['query' => $options] : [];
return $this->request($url, 'GET', $query);
}
public function post($url, $options = [])
{
$key = is_array($options) ? 'form_params' : 'body';
return $this->request($url, 'POST', [$key => $options]);
}
public function json($url, $options = [], $array = false)
{
$content = $this->request($url, 'POST', ['json' => $options]);
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;
}
public function request($url, $method = 'GET', $options = [])
{
$response = $this->getClient()->request($method, $url, $options);
return $response->getBody()->getContents();
}
}