初识 PHP-Guzzle
文档地址
Guzzle是一个使用PHP实现发送HTTP 请求,方便和web service集成的PHP 客户端模拟组件。一句话,它就像一个PHP写的浏览器。当你的服务端程序需要作为客户端来访问其他的service服务时,撸它。
- 简单的接口构建query string,POST requests,streaming large uploads/downloads,使用HTTP cookies,上传json data等。
- 可以使用相同的接口来发送同步和异步的请求
- 使用PSR-7 interface for requests, response,stream.这允许你使用其他的PSR-7兼容的库和Guzzle一起工作
- 将底层的HTTP传输层抽象屏蔽,允许你编写环境和传输协议无关的代码,即:再也没有对cURL,PHP streams, sockets,或者non-blocking event loops强依赖的代码
- 中间件系统允许你增强你的客户端行为
POST/GET请求
先下载Guzzle到本地
// 实例化客户端
$client = new GuzzleHttp\Client();
或者
$client = new GuzzleHttp\Client([
'base_uri' => 'http://localhost/test', // 根域名,可设置可不设置
'timeout' => 2.0, // 超时,可设置可不设置
]);
// url
$url = 'https://www.baidu.com';
get请求
$res = $client->request('GET', $url);
post请求
$res = $client->request('POST', $url, [
'form_params' => [
'name'=>'zhangsan',
'sex'=>'1'
]
]);
或者
$res = $client->request('POST', $url, [
'query' => [
'name'=>'zhangsan',
'sex'=>'1',
]
]);
// 返回状态码
echo $res->getStatusCode();
// 连贯操作
// $res = $client->request('GET', $url)->getBody()->getContents();
自定义header
// $api可以为空,一般为api接口后缀,也可以直接写到上面的base_uri里面,
$res = $client->request('POST/GET', '$api', [
'headers' => [
'name' => 'info'
],
'query' => [
'username' => 'webben',
'password' => '123456',
]
]);
设置IP代理
$res = $client->request('GET', $url, [
'proxy' => '100.200.30.40'
]);
cookie 访问
cookie访问和自定义header类似,只是把headers这个数组更换为 'cookies' => $cookieInfo
查看返回状态和信息
$code = $res->getStatusCode(); // 200
$reason = $res->getReasonPhrase(); // OK
echo $res->getBody();