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');
附錄