项目中使用第三方接口时,我们可以用封装好的工具----Guzzle。
Guzzle是一个PHP的 HTTP 客户端,用来轻而易举地发送请求,并集成到我们的 WEB 服务上。
接口简单:构建查询语句、POST 请求、分流上传下载大文件、使用 HTTP cookies、上传JSON 数据等等。
发送同步或异步的请求均使用相同的接口。
使用 PSR-7 接口来请求、响应、分流,允许你使用其他兼容的 PSR-7 类库与Guzzle共同开发。
抽象了底层的 HTTP 传输,允许你改变环境以及其他的代码,如:对 cURL 与PHP的流或 socket 并非重度依赖,非阻塞事件循环。
中间件系统允许你创建构成客户端行为。
Composer 安装
composer require guzzlehttp/guzzle
简单的例子
创建客户端
use GuzzleHttp\Client; $client = new Client([ // Base URI is used with relative requests 'base_uri' => 'http://httpbin.org', // You can set any number of default request options. 'timeout' => 2.0, ]);
发送请求
$response = $client->get('http://httpbin.org/get'); $response = $client->delete('http://httpbin.org/delete'); $response = $client->head('http://httpbin.org/get'); $response = $client->options('http://httpbin.org/get'); $response = $client->patch('http://httpbin.org/patch'); $response = $client->post('http://httpbin.org/post'); $response = $client->put('http://httpbin.org/put');
你可以创建一个请求,一切就绪后将请求传送给 client:
use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);
异步请求
$promise = $client->getAsync('http://httpbin.org/get'); $promise = $client->deleteAsync('http://httpbin.org/delete'); $promise = $client->headAsync('http://httpbin.org/get'); $promise = $client->optionsAsync('http://httpbin.org/get'); $promise = $client->patchAsync('http://httpbin.org/patch'); $promise = $client->postAsync('http://httpbin.org/post'); $promise = $client->putAsync('http://httpbin.org/put');
并发请求
use GuzzleHttp\Client; use GuzzleHttp\Promise; $client = new Client(['base_uri' => 'http://httpbin.org/']); // Initiate each request but do not block $promises = [ 'image' => $client->getAsync('/image'), 'png' => $client->getAsync('/image/png'), 'jpeg' => $client->getAsync('/image/jpeg'), 'webp' => $client->getAsync('/image/webp') ]; // 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['image']->getHeader('Content-Length'); echo $results['png']->getHeader('Content-Length');
上传数据
//Guzzle 为上传数据提供了一些方法。 你可以发送一个包含数据流的请求,将 body 请求参数设置成一个字符串、 fopen 返回的资源、或者一个 Psr\Http\Message\StreamInterface 的实例。 // Provide the body as a string. $r = $client->request('POST', 'http://httpbin.org/post', [ 'body' => 'raw data' ]); // Provide an fopen resource. $body = fopen('/path/to/file', 'r'); $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]); // Use the stream_for() function to create a PSR-7 stream. $body = \GuzzleHttp\Psr7\stream_for('hello!'); $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]); //上传 JSON 数据以及设置合适的头信息可以使用 json 请求参数这个简单的方式: $r = $client->request('PUT', 'http://httpbin.org/put', [ 'json' => ['foo' => 'bar'] ]);
....
官方手册
以上为手册采摘内容