之前的文章有讲到php调用curl发送http请求,但curl这种过程式的调用有时候是有点不方便的,各种参数的设置太麻烦。以至于我一写到curl就要去找找以前写的代码来拷贝。
如果使用composer的话,有一个包是挺好用的,就是GuzzleHttp。这个包的接口很简单,使用起来略微轻松。
下面是测试的代码:
require __DIR__."/vendor/autoload.php";
use GuzzleHttp\Client;
$client = new Client([
"base_uri' => 'http://www.zeroplace.cn/',
'timeout' => 2.0,
]);
$res = $client->request("GET", "/");
echo $res->getStatusCode(), "\n";
foreach ($res->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
$body = $res->getBody();
echo $body;
这个是测试代码的地址:https://github.com/gaohuia2015/test_guzzle
文档地址:http://docs.guzzlephp.org/en/latest/overview.html