-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathhttpClient.php
72 lines (62 loc) · 1.89 KB
/
httpClient.php
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
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
class HttpClient
{
private static $instance = null;
// GuzzleHttp Client
private $client;
private function __construct()
{
// 创建 Guzzle Client 实例
$this->client = new Client([
'base_uri' => 'http://as.dun.163.com',
'timeout' => 10.0,
'connect_timeout' => 10.0, // 设置连接超时
'headers' => [
'Connection' => 'keep-alive'
]
]);
}
// 获取单例实例
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function post($url, $data, $timeout)
{
try {
$response = $this->client->request('POST', $url, [
'form_params' => $data,
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
'Connection' => 'keep-alive'
],
'timeout' => $timeout
]);
return $response->getBody()->getContents();
} catch (\Exception $e) {
return 'Error: ' . $e->getMessage();
}
}
public function get($url, $params, $timeout, $headersMap)
{
$queryString = http_build_query($params);
$url = $url . "?" . $queryString;
try {
$response = $this->client->request('GET', $url, [
'headers' => $headersMap,
'verify' => false // 禁用SSL证书验证(生产环境中不推荐)
]);
$output = $response->getBody()->getContents();
echo "output:{$output}";
return $output;
} catch (\Exception $e) {
return 'Error: ' . $e->getMessage();
}
}
}
?>