-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathHttpClient.php
More file actions
84 lines (67 loc) · 2.3 KB
/
HttpClient.php
File metadata and controls
84 lines (67 loc) · 2.3 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
<?php
namespace WF\Hypernova\Http;
function getOrNull($array, $key){
return isset($array[$key]) ? $array[$key] : null;
}
class Client {
private $globalConf;
public function __construct($conf) {
$this->globalConf = $conf;
}
public function request($method, $url, $body = null, $queryParams = null, $headers = []) {
$curl = curl_init();
if (!is_null($queryParams)) {
$url .= '?' . http_build_query($queryParams);
}
$conf = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLINFO_HEADER_OUT => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $method
);
foreach ($conf as $option => $value) {
curl_setopt($curl, $option, $value);
}
if (!is_null($body)) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
}
$tmp = [];
foreach ($headers as $key => $record) {
$tmp[] = $record;
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $tmp);
try {
$rawResponse = curl_exec($curl);
} catch (\ErrorException $ex) {
throw new \Exception($ex->getMessage(), $ex->getCode(), $ex->getPrevious());
}
$response = new Response($curl, $rawResponse);
curl_close($curl); // close cURL handler
return $response;
}
public function get($url, $conf = []){
$queryParams = getOrNull($conf, 'params');
$headers = getOrNull($conf, 'headers');
return $this->request('GET', $url, null, $queryParams, $headers);
}
public function post($url, $conf = []) {
$body = getOrNull($conf, 'body');
$json = getOrNull($conf, 'json');
$queryParams = getOrNull($conf, 'params');
$headers = getOrNull($conf, 'headers');
if(!is_null($json)){
$body = json_encode($json);
if(is_null($headers)) {
$headers = [];
}
$headers[] = "Content-Type: application/json";
}
return $this->request('POST', $url, $body, $queryParams, $headers);
}
}
?>