|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @license MIT |
|
4
|
|
|
* @author zhangv |
|
5
|
|
|
*/ |
|
6
|
|
|
namespace zhangv\wechat; |
|
7
|
|
|
|
|
8
|
|
|
class HttpClient{ |
|
9
|
|
|
|
|
10
|
|
|
const GET = 'get',POST = 'post', DELETE = 'delete',PUT = 'put'; |
|
11
|
|
|
private $instance = null; |
|
12
|
|
|
private $errNo = null; |
|
13
|
|
|
private $info = null; |
|
14
|
|
|
private $timeout = 1; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct($timeout = 1) { |
|
17
|
|
|
$this->initInstance($timeout); |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
public function initInstance($timeout){ |
|
21
|
|
|
if(!$this->instance) { |
|
22
|
|
|
$this->instance = curl_init(); |
|
23
|
|
|
curl_setopt($this->instance, CURLOPT_TIMEOUT, intval($timeout)); |
|
24
|
|
|
curl_setopt($this->instance, CURLOPT_RETURNTRANSFER, true); |
|
25
|
|
|
curl_setopt($this->instance, CURLOPT_FOLLOWLOCATION, true); |
|
26
|
|
|
curl_setopt($this->instance, CURLOPT_SSL_VERIFYPEER, false); |
|
27
|
|
|
} |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function get($url,$params = array(),$headers = array(),$opts = array()) { |
|
31
|
|
|
if (!$this->instance) $this->initInstance($this->timeout); |
|
32
|
|
|
if($params && count($params) > 0) $url .= '?' . http_build_query($params); |
|
33
|
|
|
curl_setopt($this->instance, CURLOPT_URL, $url); |
|
34
|
|
|
curl_setopt($this->instance, CURLOPT_HTTPGET, true); |
|
35
|
|
|
curl_setopt($this->instance, CURLOPT_HTTPHEADER, $headers); |
|
36
|
|
|
curl_setopt_array($this->instance,$opts); |
|
37
|
|
|
$result = $this->execute(); |
|
38
|
|
|
curl_close($this->instance); |
|
39
|
|
|
$this->instance = null; |
|
40
|
|
|
return $result; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function post($url, $params = array(),$headers = array(),$opts = array()) { |
|
44
|
|
|
if (!$this->instance) $this->initInstance($this->timeout); |
|
45
|
|
|
curl_setopt($this->instance, CURLOPT_URL, $url); |
|
46
|
|
|
curl_setopt($this->instance, CURLOPT_POST, true); |
|
47
|
|
|
curl_setopt($this->instance, CURLOPT_POSTFIELDS, $params); |
|
48
|
|
|
curl_setopt($this->instance, CURLOPT_HTTPHEADER, $headers); |
|
49
|
|
|
curl_setopt_array($this->instance,$opts); |
|
50
|
|
|
$result = $this->execute(); |
|
51
|
|
|
curl_close($this->instance); |
|
52
|
|
|
$this->instance = null; |
|
53
|
|
|
return $result; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
private function execute() { |
|
57
|
|
|
$result = curl_exec($this->instance); |
|
58
|
|
|
$this->errNo = curl_errno($this->instance); |
|
59
|
|
|
$this->info = curl_getinfo($this->instance); |
|
60
|
|
|
return $result; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
public function getInfo(){ |
|
64
|
|
|
return $this->info; |
|
65
|
|
|
} |
|
66
|
|
|
} |