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