Guzzle 介绍php
Guzzle 是一款简单、易用的 PHP HTTP 客户端。html
它能够快速的集成到 WEB 项目中,帮助咱们很是方便的发送 HTTP 请求。git
Guzzle 特色github
接口简单json
支持使用 curl,PHP streams,sockets等各类方式。promise
支持同步和异步请求cookie
遵循 PSR7 规范,能够集成其余的符合 psr7 规范的类库,自定义处理逻辑并发
安装composer
使用 composer 安装,很是方便curl
composer require --prefer-dist guzzlehttp/guzzle
快速入门
1.初始化客户端
use GuzzleHttp\Client; options = [ 'base_uri' => 'http://guzzle.testhttp.com', 'connect_timeout' => 1, 'timeout' => 3, ]; $client = new Client($options);
2.发送body请求
$client->request('POST', '/post', ['body' => 'this is post body']);
3.发送表单请求
$client->request('POST', '/post', [ 'form_params' => [ 'user_id' => 1, 'user_name' => 'hello world!' ] ]);
4.json 请求
$client->request('POST', '/post', ['json' => ['data' => 'hello world!']]);
5.使用cookie
$params = ['json' => ['data' => 'hello world!']]; $cookieJar = CookieJar::fromArray(['cookieName' => 'testCookie'], 'guzzle.testhttp.com'); $param['cookies'] = $cookieJar; $client->request('POST', '/post', $params);
6.multipart
$client->request('POST', '/post', [ 'multipart' => [ [ 'name' => 'baz', 'contents' => fopen('/path/to/file', 'r') ], [ 'name' => 'qux', 'contents' => fopen('/path/to/file', 'r'), 'filename' => 'custom_filename.txt' ], ] ]);
7.异步请求
use Psr\Http\Message\ResponseInterface; use GuzzleHttp\Exception\RequestException; $promise = $client->requestAsync('POST', '/post', ['json' => ['data' => 'hello world!']]); $promise->then( function (ResponseInterface $res) { echo $res->getStatusCode() . "\n"; }, function (RequestException $e) { echo $e->getMessage() . "\n"; echo $e->getRequest()->getMethod(); } );
8.并发请求
use GuzzleHttp\Client; use GuzzleHttp\Promise; $client = new Client(['base_uri' => 'http://guzzle.testhttp.com/']); // Initiate each request but do not block $promises = [ 'a' => $client->requestAsync('POST', '/post', ['json' => ['data' => 'hello test1!']]), 'b' => $client->requestAsync('POST', '/post', ['json' => ['data' => 'hello test2!']]), 'b' => $client->requestAsync('POST', '/post', ['json' => ['data' => 'hello test3!']]), ]; // Wait on all of the requests to complete. $results = Promise\unwrap($promises); // You can access each result using the key provided to the unwrap // function. echo $results['a']->getBody()->getContents(); // body 也有实现 __toString()调用getContents() echo $results['b']->getHeader('Content-Length');
附录