Guzzle是一個PHP的HTTP客戶端,用來垂手可得地發送請求,並集成到咱們的WEB服務上。php
Github地址:guzzle/guzzlehtml
官方文檔:http://docs.guzzlephp.org/en/...git
中文文檔:http://guzzle-cn.readthedocs....github
執行composer命令:web
composer require guzzlehttp/guzzle
引入Composer自動加載類:json
require ‘vendor/autoload.php’;
經過Composer更新Guzzle:api
composer.phar update
$client = new \GuzzleHttp\Client(); $res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); echo $res->getStatusCode(); // 200 echo $res->getHeaderLine('content-type'); // 'application/json; charset=utf8' echo $res->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' // 發送一個異步請求 $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); $promise = $client->sendAsync($request)->then(function ($response) { echo 'I completed! ' . $response->getBody(); }); $promise->wait();
經過實例化Client類建立一個客戶端:promise
<?php use GuzzleHttp\Client; $client = new Client([ // 基URI 'base_uri' => 'http://httpbin.org', // 設置默認請求參數 'timeout' => 2.0, ]);
Client對象的方法能夠很容易的發送請求:cookie
<?php $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');
或者建立一個請求,一切就緒後再發送請求:併發
<?php use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);
直接用Client提供的方法來建立異步請求:
<?php $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');
或者使用Client的 sendAsync() and requestAsync() 方法:
<?php // 建立一個PSR-7請求對象 $headers = ['X-Foo' => 'Bar']; $body = 'Hello!'; $request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body); // 若是不須要進去請求實例 $promise = $client->requestAsync('GET', 'http://httpbin.org/get');
使用 then() 來調用返回值,成功使用 Psr\Http\Message\ResponseInterface 處理器,不然拋出一個異常:
<?php use Psr\Http\Message\ResponseInterface; use GuzzleHttp\Exception\RequestException; $promise = $client->requestAsync('GET', 'http://httpbin.org/get'); $promise->then( function (ResponseInterface $res) { echo $res->getStatusCode() . "\n"; }, function (RequestException $e) { echo $e->getMessage() . "\n"; echo $e->getRequest()->getMethod(); } );
使用Promise和異步請求來同時發送多個請求:
<?php use GuzzleHttp\Client; use GuzzleHttp\Promise; $client = new Client(['base_uri' => 'http://httpbin.org/']); // 初始化每個非阻塞請求 $promises = [ 'image' => $client->getAsync('/image'), 'png' => $client->getAsync('/image/png'), 'jpeg' => $client->getAsync('/image/jpeg'), 'webp' => $client->getAsync('/image/webp') ]; // 等待請求完成 $results = Promise\unwrap($promises); // 經過鍵名接收每個結果 // function. echo $results['image']->getHeader('Content-Length'); echo $results['png']->getHeader('Content-Length');
當你想發送不肯定數量的請求時,可使用 GuzzleHttp\Pool 對象:
<?php use GuzzleHttp\Pool; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; $client = new Client(); $requests = function ($total) { $uri = 'http://127.0.0.1:8126/guzzle-server/perf'; for ($i = 0; $i < $total; $i++) { yield new Request('GET', $uri); } }; $pool = new Pool($client, $requests(100), [ 'concurrency' => 5, 'fulfilled' => function ($response, $index) { // 每一個成功的請求 }, 'rejected' => function ($reason, $index) { // 每一個失敗的請求 }, ]); // 初始化傳輸和建立受權 $promise = $pool->promise(); // 等待請求池完成 $promise->wait();
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
// 檢查是否存在頭信息 if ($response->hasHeader('Content-Length')) { echo "It exists"; } // 獲取頭信息 echo $response->getHeader('Content-Length'); // 獲取全部響應頭信息 foreach ($response->getHeaders() as $name => $values) { echo $name . ': ' . implode(', ', $values) . "\r\n"; }
$body = $response->getBody(); // 隱式轉換成字符串並輸出 echo $body; // 顯示轉換body成字符串 $stringBody = (string) $body; // 從body中讀取10字節(bytes) $tenBytes = $body->read(10); // 將正文的剩餘內容做爲字符串讀取 $remainingBytes = $body->getContents();
$response = $client->request('GET', 'http://httpbin.org?foo=bar');
$client->request('GET', 'http://httpbin.org', [ 'query' => ['foo' => 'bar'] ]);
$client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
Guzzle還提供了一些其它有用的功能
具體的能夠查看官方文檔。
END