https://guzzle-cn.readthedocs.io/zh_CN/latest/
Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。
测试用的windows环境
安装
composer require guzzlehttp/guzzle:~6.0
使用
use GuzzleHttp\Client;
$client = new Client();
$url = "http://www.xxx.com";
$response = $client->post($url, ['json'=>$data]);
//如果状态时200,并且返回内容是否为 ok
if ($response->getStatusCode() == 200 && strcasecmp('ok', $response->getBody()->getContents()) == 0) {
//作出处理
} else {
//作出处理
}
- Guzzle的常用GET请求示例:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'https://api.example.com/data');
$status = $response->getStatusCode();
$body = $response->getBody()->getContents();
echo "Status code: " . $status . PHP_EOL;
echo "Response body: " . $body . PHP_EOL;
- Guzzle的常用POST请求示例:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('POST', 'https://api.example.com/submit', [
'form_params' => [
'name' => 'John Doe',
'email' => '[email protected]',
'message' => 'Hello, Guzzle!'
]
]);
$status = $response->getStatusCode();
$body = $response->getBody()->getContents();
echo "Status code: " . $status . PHP_EOL;
echo "Response body: " . $body . PHP_EOL;
以上示例中,我们使用了Guzzle的Client
类来发送GET和POST请求。在GET请求中,我们使用request
方法指定请求的方法为GET,并传入请求的URL。在POST请求中,我们使用request
方法指定请求的方法为POST,并传入请求的URL和要提交的表单参数。