Guzzle使用記錄

1. 什麼是Guzzle?

Guzzle是一個PHP的HTTP客戶端,用來垂手可得地發送請求,並集成到咱們的WEB服務上。php

  • 接口簡單:構建查詢語句、POST請求、分流上傳下載大文件、使用HTTP cookies、上傳JSON數據等等。
  • 發送同步或異步的請求均使用相同的接口。
  • 使用PSR-7接口來請求、響應、分流,容許你使用其餘兼容的PSR-7類庫與Guzzle共同開發。
  • 抽象了底層的HTTP傳輸,容許你改變環境以及其餘的代碼,如:對cURL與PHP的流或socket並不是重度依賴,非阻塞事件循環。
  • 中間件系統容許你建立構成客戶端行爲。

Github地址:guzzle/guzzlehtml

官方文檔:http://docs.guzzlephp.org/en/...git

中文文檔:http://guzzle-cn.readthedocs....github

2. 安裝Guzzle

2.1 經過composer安裝

執行composer命令:web

composer require guzzlehttp/guzzle

引入Composer自動加載類:json

require ‘vendor/autoload.php’;

經過Composer更新Guzzle:api

composer.phar update

3. 例子

$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();

4. 發送請求

4.1 建立客戶端

經過實例化Client類建立一個客戶端:promise

<?php
use GuzzleHttp\Client;

$client = new Client([
    // 基URI
    'base_uri' => 'http://httpbin.org',
    // 設置默認請求參數
    'timeout'  => 2.0,
]);

4.2 發送請求

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]);

4.3 異步請求

直接用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();
    }
);

4.4 併發請求

使用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();

5. 響應

5.1 獲取響應的狀態碼

$code = $response->getStatusCode(); // 200

5.2 獲取緣由短語(reason phrase)

$reason = $response->getReasonPhrase(); // OK

5.3 獲取頭信息(header)

// 檢查是否存在頭信息
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";
}

5.4 獲取響應的主體部分(body)

$body = $response->getBody();
// 隱式轉換成字符串並輸出
echo $body;
// 顯示轉換body成字符串
$stringBody = (string) $body;
// 從body中讀取10字節(bytes)
$tenBytes = $body->read(10);
// 將正文的剩餘內容做爲字符串讀取
$remainingBytes = $body->getContents();

6. 參數

6.1 在請求的URI中設置查詢字符串

$response = $client->request('GET', 'http://httpbin.org?foo=bar');

6.2 使用 query 請求參數來聲明查詢字符串參數

$client->request('GET', 'http://httpbin.org', [
    'query' => ['foo' => 'bar']
]);

6.3 提供一個字符串做爲 query 請求參數

$client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);

7. 其它

Guzzle還提供了一些其它有用的功能

具體的能夠查看官方文檔。

END

相關文章
相關標籤/搜索