php 請求庫 guzzle 的使用


Guzzle是一個PHP的HTTP客戶端,用來輕而易舉地發送請求,並集成到我們的WEB服務上。

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

官方文檔:https://guzzle-cn.readthedocs.io/zh_CN/latest/

github:https://github.com/guzzle/guzzle

環境要求

  1. PHP 5.5.0
  2. 使用PHP的流, allow_url_fopen 必須在php.ini中啟用。
  3. 要使用cURL,你必須已經有版本cURL >= 7.19.4,並且編譯了OpenSSL 與 zlib。

如果沒有安裝cURL,Guzzle處理HTTP請求的時候不再使用cURL,而是使用PHP流處理,或者你也可以提供自己的發送HTTP請求的處理方式。

安裝

composer require guzzlehttp/guzzle:~6.0

該頁面提供了Guzzle的快速入門以及列子,如果你還沒有安裝Guzzle請前往 安裝 頁面。

發送請求

你可以使用Guzzle的 GuzzleHttp\ClientInterface 對象來發送請求。

創建客戶端

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

Client對象可以接收一個包含參數的數組:

  • base_uri

    (string|UriInterface) 基URI用來合並到相關URI,可以是一個字符串或者UriInterface的實例,當提供了相關uri,將合並到基URI,遵循的規則請參考 RFC 3986, section 2 章節。

    // Create a client with a base URI 
    $client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']); 
    // Send a request to https://foo.com/api/test 
    $response = $client->request('GET', 'test'); 
    // Send a request to https://foo.com/root 
    $response = $client->request('GET', '/root');
    

    不想閱讀RFC 3986?這里有一些關於 base_uri 與其他URI處理器的快速例子:

    http://foo.com``/bar``
    http://foo.com/bar``
    http://foo.com/foo``/bar``
    http://foo.com/bar``
    http://foo.com/foo``bar``
    http://foo.com/bar``
    http://foo.com/foo/``bar``
    http://foo.com/foo/bar``
    http://foo.com``
    http://baz.com``http://baz.com``
    http://foo.com/?bar``bar``
    http://foo.com/bar
    
  • handler

    傳輸HTTP請求的(回調)函數。 該函數被調用的時候包含 Psr7\Http\Message\RequestInterface 以及參數數組,必須返回 GuzzleHttp\Promise\PromiseInterface ,成功時滿足 Psr7\Http\Message\ResponseInterfacehandler 是一個構造方法,不能在請求參數里被重寫。

  • ...

    (混合) 構造方法中傳入的其他所有參數用來當作每次請求的默認參數。

發送請求

Client對象的方法可以很容易的發送請求:

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

Client對象為傳輸請求提供了非常靈活的處理器方式,包括請求參數、每次請求使用的中間件以及傳送多個相關請求的基URI。

你可以在 Handlers and Middleware 頁面找到更多關於中間件的內容。

異步請求

你可以使用Client提供的方法來創建異步請求:

$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() 方法:

use GuzzleHttp\Psr7\Request;

// Create a PSR-7 request object to send
$headers = ['X-Foo' => 'Bar'];
$body = 'Hello!';
$request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);

// Or, if you don't need to pass in a request instance:
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');

這些方法返回了Promise對象,該對象實現了由 Guzzle promises library 提供的 Promises/A+ spec ,這意味着你可以使用 then() 來調用返回值,成功使用 Psr\Http\Message\ResponseInterface 處理器,否則拋出一個異常。

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和異步請求來同時發送多個請求:

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

當你想發送不確定數量的請求時,可以使用 GuzzleHttp\Pool 對象:

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) {
        // this is delivered each successful response
    },
    'rejected' => function ($reason, $index) {
        // this is delivered each failed request
    },
]);

// Initiate the transfers and create a promise
$promise = $pool->promise();

// Force the pool of requests to complete.
$promise->wait();

使用響應

前面的例子里,我們取到了 $response 變量,或者從Promise得到了響應,Response對象實現了一個PSR-7接口 Psr\Http\Message\ResponseInterface , 包含了很多有用的信息。

你可以獲取這個響應的狀態碼和和原因短語(reason phrase):

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

你可以從響應獲取頭信息(header):

// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
    echo "It exists";
}

// Get a header from the response.
echo $response->getHeader('Content-Length');

// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values) . "\r\n";
}

使用 getBody 方法可以獲取響應的主體部分(body),主體可以當成一個字符串或流對象使用

$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();

查詢字符串參數

你可以有多種方式來提供請求的查詢字符串 你可以在請求的URI中設置查詢字符串:

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

你可以使用 query 請求參數來聲明查詢字符串參數:

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

提供的數組參數將會使用PHP的 http_build_query

最后,你可以提供一個字符串作為 query 請求參數:

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

上傳數據

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

POST/表單請求

除了使用 body 參數來指定請求數據外,Guzzle為發送POST數據提供了有用的方法。

發送表單字段

發送 application/x-www-form-urlencoded POST請求需要你傳入 form_params 數組參數,數組內指定POST的字段。

$response = $client->request('POST', 'http://httpbin.org/post', [
    'form_params' => [
        'field_name' => 'abc',
        'other_field' => '123',
        'nested_field' => [
            'nested' => 'hello'
        ]
    ]
]);

發送表單文件

你可以通過使用 multipart 請求參數來發送表單(表單enctype屬性需要設置 multipart/form-data )文件, 該參數接收一個包含多個關聯數組的數組,每個關聯數組包含一下鍵名:

  • name: (必須,字符串) 映射到表單字段的名稱。
  • contents: (必須,混合) 提供一個字符串,可以是 fopen 返回的資源、或者一個

Psr\Http\Message\StreamInterface 的實例。

$response = $client->request('POST', 'http://httpbin.org/post', [
    'multipart' => [
        [
            'name'     => 'field_name',
            'contents' => 'abc'
        ],
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'other_file',
            'contents' => 'hello',
            'filename' => 'filename.txt',
            'headers'  => [
                'X-Foo' => 'this is an extra header to include'
            ]
        ]
    ]
]);

Cookies

Guzzle可以使用 cookies 請求參數為你維護一個cookie會話,當發送一個請求時, cookies 選項必須設置成 GuzzleHttp\Cookie\CookieJarInterface 的實例。

// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
    'cookies' => $jar
]);

You can set cookies to true in a client constructor if you would like to use a shared cookie jar for all requests.

// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');

重定向

如果你沒有告訴Guzzle不要重定向,Guzzle會自動的進行重定向,你可以使用 allow_redirects 請求參數來自定義重定向行為。

  • 設置成 true 時將啟用最大數量為5的重定向,這是默認設置。
  • 設置成 false 來禁用重定向。
  • 傳入一個包含 max 鍵名的關聯數組來聲明最大重定向次數,提供可選的 strict 鍵名來聲明是否使用嚴格的RFC標准重定向 (表示使用POST請求重定向POST請求 vs 大部分瀏覽器使用GET請求重定向POST請求)。
$response = $client->request('GET', 'http://github.com');
echo $response->getStatusCode();
// 200

下面的列子表示重定向被禁止:

$response = $client->request('GET', 'http://github.com', [
    'allow_redirects' => false
]);
echo $response->getStatusCode();
// 301

異常

請求傳輸過程中出現的錯誤Guzzle將會拋出異常。

  • 在發送網絡錯誤(連接超時、DNS錯誤等)時,將會拋出 GuzzleHttp\Exception\RequestException 異常。 該異常繼承自 GuzzleHttp\Exception\TransferException ,捕獲這個異常可以在傳輸請求過程中拋出異常。

    use GuzzleHttp\Exception\RequestException;
    
    try {
        $client->request('GET', 'https://github.com/_abc_123_404');
    } catch (RequestException $e) {
        echo $e->getRequest();
        if ($e->hasResponse()) {
            echo $e->getResponse();
        }
    }
    
  • GuzzleHttp\Exception\ConnectException 異常發生在網絡錯誤時, 該異常繼承自 GuzzleHttp\Exception\RequestException

  • 如果 http_errors 請求參數設置成true,在400級別的錯誤的時候將會拋出 GuzzleHttp\Exception\ClientException 異常, 該異常繼承自 GuzzleHttp\Exception\BadResponseException GuzzleHttp\Exception\BadResponseException 繼承自 GuzzleHttp\Exception\RequestException

    use GuzzleHttp\Exception\ClientException;
    
    try {
        $client->request('GET', 'https://github.com/_abc_123_404');
    } catch (ClientException $e) {
        echo $e->getRequest();
        echo $e->getResponse();
    }
    
  • 如果 http_errors 請求參數設置成true,在500級別的錯誤的時候將會拋出 GuzzleHttp\Exception\ServerException 異常。 該異常繼承自 GuzzleHttp\Exception\BadResponseException

  • GuzzleHttp\Exception\TooManyRedirectsException 異常發生在重定向次數過多時, 該異常繼承自 GuzzleHttp\Exception\RequestException

上述所有異常均繼承自 GuzzleHttp\Exception\TransferException

環境變量

Guzzle提供了一些可自定義的環境變量:

  • GUZZLE_CURL_SELECT_TIMEOUT

    當在curl處理器時使用 curl_multi_select() 控制了 curl_multi_* 需要使用到的持續時間, 有些系統實現PHP的 curl_multi_select() 存在問題,調用該函數時總是等待超時的最大值。

  • HTTP_PROXY

    定義了使用http協議發送請求時使用的代理。

  • HTTPS_PROXY

    定義了使用https協議發送請求時使用的代理。

相關ini設置

Guzzle配置客戶端時可以利用PHP的ini配置。

請求選項

你可以通過設置Client的 請求選項 來自定義請求,請求參數控制請求的各個方面,包括頭信息、查詢字符串參數、超時、請求主體等。

下述所有的列子都使用下面的Client:

$client = new GuzzleHttp\Client(['base_uri' => 'http://httpbin.org']);

allow_redirects

  • 摘要

    描述請求的重定向行為

  • 類型

    boolarray

  • 默認值

    [
        'max'             => 5,
        'strict'          => false,
        'referer'         => true,
        'protocols'       => ['http', 'https'],
        'track_redirects' => false
    ]
    
  • 常量

    GuzzleHttp\RequestOptions::ALLOW_REDIRECTS

設置成 false 禁用重定向。

$res = $client->request('GET', '/redirect/3', ['allow_redirects' => false]);
echo $res->getStatusCode();
// 302

設置成 true (默認設置) 來啟用默認最大次數為5的重定向。

$res = $client->request('GET', '/redirect/3');
echo $res->getStatusCode();
// 200

你也可以傳送一個包含了以下鍵值對的關聯數組:

  • max: (int, 默認為5) 允許重定向次數的最大值。
  • strict: (bool, 默認為false) 設置成 true 使用嚴格模式重定向 嚴格RFC模式重定向表示使用POST請求重定向POST請求 vs 大部分瀏覽器使用GET請求重定向POST請求。
  • referer: (bool, 默認為true) 設置成 false 重定向時禁止添加Refer頭信息。
  • protocols: (array, 默認為['http', 'https']) 指定允許重定向的協議。
  • on_redirect: (callable) 發生重定向時調用PHP回調,包含了原始的請求以及接收到重定向的響應,on_redirect的任何返回將會被忽略。
  • track_redirects: (bool) 當設置成 true 時,每個重定向的URI將會按序被跟蹤頭信息 X-Guzzle-Redirect-History
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;

$onRedirect = function(
    RequestInterface $request,
    ResponseInterface $response,
    UriInterface $uri
) {
    echo 'Redirecting! ' . $request->getUri() . ' to ' . $uri . "\n";
};

$res = $client->request('GET', '/redirect/3', [
    'allow_redirects' => [
        'max'             => 10,        // allow at most 10 redirects.
        'strict'          => true,      // use "strict" RFC compliant redirects.
        'referer'         => true,      // add a Referer header
        'protocols'       => ['https'], // only allow https URLs
        'on_redirect'     => $onRedirect,
        'track_redirects' => true
    ]
]);

echo $res->getStatusCode();
// 200

echo $res->getHeaderLine('X-Guzzle-Redirect-History');
// http://first-redirect, http://second-redirect, etc...

auth

  • 摘要

    傳入HTTP認證參數的數組來使用請求,該數組索引[0]為用戶名、索引[1]為密碼,索引[2]為可選的內置認證類型。傳入 null 進入請求認證。

  • 類型

    arraystringnull

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::AUTH

內置認證類型如下:

  • basic

    Authorization 頭信息使用 HTTP基礎認證 (如果沒有指定的話為默認設置)。

$client->request('GET', '/get', ['auth' => ['username', 'password']]);
$client->request('GET', '/get', [
    'auth' => ['username', 'password', 'digest']
]);

body

  • 摘要

    body 選項用來控制一個請求(比如:PUT, POST, PATCH)的主體部分。

  • 類型

    stringfopen() resourcePsr\Http\Message\StreamInterface

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::BODY

可以設置成下述類型:

  • string

    // You can send requests that use a string as the message body.
    $client->request('PUT', '/put', ['body' => 'foo']);
    
  • resource returned from fopen()

    // You can send requests that use a stream resource as the body.
    $resource = fopen('http://httpbin.org', 'r');
    $client->request('PUT', '/put', ['body' => $resource]);
    
  • Psr\Http\Message\StreamInterface

    // You can send requests that use a Guzzle stream object as the body
    $stream = GuzzleHttp\Psr7\stream_for('contents...');
    $client->request('POST', '/post', ['body' => $stream]);
    

cert

  • 摘要

    設置成指定PEM格式認證文件的路徑的字符串,如果需要密碼,需要設置成一個數組,其中PEM文件在第一個元素,密碼在第二個元素。

  • 類型

    stringarray

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::CERT

$client->request('GET', '/', ['cert' => ['/path/server.pem', 'password']]);

cookies

  • 摘要

    聲明是否在請求中使用cookie,或者要使用的cookie jar,或者要發送的cookie。

  • 類型

    GuzzleHttp\Cookie\CookieJarInterface

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::COOKIES

你必須聲明cookie選項為 GuzzleHttp\Cookie\CookieJarInterfacefalse

$jar = new \GuzzleHttp\Cookie\CookieJar();
$client->request('GET', '/get', ['cookies' => $jar]);

connect_timeout

  • 摘要

    表示等待服務器響應超時的最大值,使用 0 將無限等待 (默認行為).

  • 類型

    float

  • 默認值

    0

  • 常量

    GuzzleHttp\RequestOptions::CONNECT_TIMEOUT

// Timeout if the client fails to connect to the server in 3.14 seconds.
$client->request('GET', '/delay/5', ['connect_timeout' => 3.14]);

debug

  • 摘要

    設置成 true 或設置成一個 fopen() 返回的流來啟用調試輸出發送請求的處理器, 比如,當使用cURL傳輸請求,cURL的 CURLOPT_VERBOSE 的冗長將會發出, 當使用PHP流,流處理的提示將會發生。 如果設置為true,輸出到PHP標准輸出文件,如果提供了PHP流,將會輸出到流。

  • 類型

    boolfopen() resource

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::DEBUG

$client->request('GET', '/get', ['debug' => true]);

執行上面的例子將會輸出類似下面的結果:

* About to connect() to httpbin.org port 80 (#0)
*   Trying 107.21.213.98... * Connected to httpbin.org (107.21.213.98) port 80 (#0)
> GET /get HTTP/1.1
Host: httpbin.org
User-Agent: Guzzle/4.0 curl/7.21.4 PHP/5.5.7

< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Content-Type: application/json
< Date: Sun, 16 Feb 2014 06:50:09 GMT
< Server: gunicorn/0.17.4
< Content-Length: 335
< Connection: keep-alive
<
* Connection #0 to host httpbin.org left intact

decode_content

  • 摘要

    聲明是否自動解碼 Content-Encoding 響應 (gzip, deflate等) 。

  • 類型

    stringbool

  • 默認值

    true

  • 常量

    GuzzleHttp\RequestOptions::DECODE_CONTENT

該選項可以用來控制Content-Encoding如何響應主體的,默認 decode_content 設置為 true,表示Guzzle將自動解碼gzip,deflate等響應。

當設置成 false ,響應的主體將不會被解碼,意味着字節將毫無變化的通過處理器。

// Request gzipped data, but do not decode it while downloading
$client->request('GET', '/foo.js', [
    'headers'        => ['Accept-Encoding' => 'gzip'],
    'decode_content' => false
]);

當設置成字符串,響應的字節將被解碼,提供 decode_content 選項的字符串將作為請求的 Accept-Encoding 報文頭。

// Pass "gzip" as the Accept-Encoding header.
$client->request('GET', '/foo.js', ['decode_content' => 'gzip']);

delay

  • 摘要

    發送請求前延遲的毫秒數值

  • 類型

    integerfloat

  • 默認值

    null

  • 常量

    GuzzleHttp\RequestOptions::DELAY

expect

  • 摘要

    控制"Expect: 100-Continue"報文頭的行為。

  • 類型

    boolinteger

  • 默認值

    1048576

  • 常量

    GuzzleHttp\RequestOptions::EXPECT

設置成 true 來為所有發送主體的請求啟用 "Expect: 100-Continue" 報文頭; 設置成 false 來為所有的請求禁用 "Expect: 100-Continue" 報文頭; 設置成一個數值,有效載荷的大小必須大於預計發送的值,設置成數值將會為所有不確定有效載荷大小或主體不能確定指針位置的請求發送Expect報文頭,

默認情況下,當請求的主體大於1MB以及請求使用的HTTP/1.1,Guzzle將會添加 "Expect: 100-Continue" 報文頭。

form_params

  • 摘要

    用來發送一個 application/x-www-form-urlencoded POST請求.

  • 類型

    array

  • 常量

    GuzzleHttp\RequestOptions::FORM_PARAMS

關聯數組由表單字段鍵值對構成,每個字段值可以是一個字符串或一個包含字符串元素的數組。 當沒有准備 "Content-Type" 報文頭的時候,將設置為 "application/x-www-form-urlencoded"。

$client->request('POST', '/post', [
    'form_params' => [
        'foo' => 'bar',
        'baz' => ['hi', 'there!']
    ]
]);

headers

  • 摘要

    要添加到請求的報文頭的關聯數組,每個鍵名是header的名稱,每個鍵值是一個字符串或包含代表頭字段字符串的數組。

  • 類型

    array

  • Defaults

    None

  • 常量

    GuzzleHttp\RequestOptions::HEADERS

// Set various headers on a request
$client->request('GET', '/get', [
    'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ]
]);

創建Client的時候頭信息可以作為默認選項添加,當頭信息使用默認選項時,它們只能在請求沒有包含特殊頭信息的時候生效, 這包括了Client的 send()sendAsync() 方法,以及Client創建的請求(比如 request()requestAsync())。

$client = new GuzzleHttp\Client(['headers' => ['X-Foo' => 'Bar']]);

// Will send a request with the X-Foo header.
$client->request('GET', '/get');

// Sets the X-Foo header to "test", which prevents the default header
// from being applied.
$client->request('GET', '/get', ['headers' => ['X-Foo' => 'test']);

// Will disable adding in default headers.
$client->request('GET', '/get', ['headers' => null]);

// Will not overwrite the X-Foo header because it is in the message.
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://foo.com', ['X-Foo' => 'test']);
$client->send($request);

// Will overwrite the X-Foo header with the request option provided in the
// send method.
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://foo.com', ['X-Foo' => 'test']);
$client->send($request, ['headers' => ['X-Foo' => 'overwrite']]);

http_errors

  • 摘要

    設置成 false 來禁用HTTP協議拋出的異常(如 4xx 和 5xx 響應),默認情況下HTPP協議出錯時會拋出異常。

  • 類型

    bool

  • 默認值

    true

  • 常量

    GuzzleHttp\RequestOptions::HTTP_ERRORS

$client->request('GET', '/status/500');
// Throws a GuzzleHttp\Exception\ServerException

$res = $client->request('GET', '/status/500', ['http_errors' => false]);
echo $res->getStatusCode();
// 500

json

  • 摘要

    json 選項用來輕松將JSON數據當成主體上傳, 如果沒有設置Content-Type頭信息的時候會設置成 application/json

  • 類型

    能夠 json_encode() 操作的PHP類型。

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::JSON

$response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);

這里的例子使用了 tap 中間件用來查看發送了什么請求。

use GuzzleHttp\Middleware;

// Grab the client's handler instance.
$clientHandler = $client->getConfig('handler');
// Create a middleware that echoes parts of the request.
$tapMiddleware = Middleware::tap(function ($request) {
    echo $request->getHeader('Content-Type');
    // application/json
    echo $request->getBody();
    // {"foo":"bar"}
});

$response = $client->request('PUT', '/put', [
    'json'    => ['foo' => 'bar'],
    'handler' => $tapMiddleware($clientHandler)
]);

multipart

  • 摘要

    設置請求的主體為 multipart/form-data 表單。

  • 類型

    array

  • 常量

    GuzzleHttp\RequestOptions::MULTIPART

multipart 的值是一個關聯數組,每個元素包含以下鍵值對:

  • name: (string, required) 表單字段名稱
  • contents: (StreamInterface/resource/string, required) 表單元素中要使用的數據
  • headers: (array) 可選的表單元素要使用的鍵值對數組
  • filename: (string) 可選的作為要發送的文件名稱
$client->request('POST', '/post', [
    'multipart' => [
        [
            'name'     => 'foo',
            'contents' => 'data',
            'headers'  => ['X-Baz' => 'bar']
        ],
        [
            'name'     => 'baz',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'qux',
            'contents' => fopen('/path/to/file', 'r'),
            'filename' => 'custom_filename.txt'
        ],
    ]
]);

on_headers

  • 摘要

    回調函數,當響應的HTTP頭信息被接收且主體部分還未開始下載的時候調用。

  • 類型

    callable

  • 常量

    GuzzleHttp\RequestOptions::ON_HEADERS

該回調接收 Psr\Http\ResponseInterface 對象。 如果該回調拋出異常,與響應相關的Promise將會接收到 GuzzleHttp\Exception\RequestException 拋出的異常。

在數據寫入下游之前,你應該需要知道接收到的頭信息與狀態碼。

// Reject responses that are greater than 1024 bytes.
$client->request('GET', 'http://httpbin.org/stream/1024', [
    'on_headers' => function (ResponseInterface $response) {
        if ($response->getHeaderLine('Content-Length') > 1024) {
            throw new \Exception('The file is too big!');
        }
    }
]);

on_stats

  • 摘要

    on_stats 允許你獲取請求傳輸數據統計以及處理器在底層傳輸的詳情. on_stats 是個回調,當處理器完成傳輸一個請求的時候被調用。 該回調被調用請求傳輸數據統計、接收到響應,或遇到錯誤,包含發送請求數據時間的總量。

  • 類型

    callable

  • 常量

    GuzzleHttp\RequestOptions::ON_STATS

該回調接收 GuzzleHttp\TransferStats 對象。

use GuzzleHttp\TransferStats;

$client = new GuzzleHttp\Client();

$client->request('GET', 'http://httpbin.org/stream/1024', [
    'on_stats' => function (TransferStats $stats) {
        echo $stats->getEffectiveUri() . "\n";
        echo $stats->getTransferTime() . "\n";
        var_dump($stats->getHandlerStats());

        // You must check if a response was received before using the
        // response object.
        if ($stats->hasResponse()) {
            echo $stats->getResponse()->getStatusCode();
        } else {
            // Error data is handler specific. You will need to know what
            // type of error data your handler uses before using this
            // value.
            var_dump($stats->getHandlerErrorData());
        }
    }
]);

proxy

  • 摘要

    傳入字符串來指定HTTP代理,或者為不同代理指定不同協議的數組。

  • 類型

    stringarray

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::PROXY

傳入字符串為所有協議指定一個代理:

$client->request('GET', '/', ['proxy' => 'tcp://localhost:8125']);

傳入關聯數組來為特殊的URI Scheme指定特色的HTTP代理(比如"http", "https") 提供一個 no 鍵值對來提供一組不需要使用代理的主機名。

$client->request('GET', '/', [
    'proxy' => [
        'http'  => 'tcp://localhost:8125', // Use this proxy with "http"
        'https' => 'tcp://localhost:9124', // Use this proxy with "https",
        'no' => ['.mit.edu', 'foo.com']    // Don't use a proxy with these
    ]
]);

query

  • 摘要

    要添加到請求的查詢字符串的關聯數組或查詢字符串。

  • 類型

    arraystring

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::QUERY

// Send a GET request to /get?foo=bar
$client->request('GET', '/get', ['query' => ['foo' => 'bar']]);

query 選項查詢字符串指定,將會覆蓋在請求時提供的查詢字符串值。

// Send a GET request to /get?foo=bar
$client->request('GET', '/get?abc=123', ['query' => ['foo' => 'bar']]);

sink

  • 摘要

    聲明響應的主體部分將要保存的位置。

  • 類型

    string (path to file on disk)fopen() resourcePsr\Http\Message\StreamInterface

  • 默認值

    PHP temp stream

  • 常量

    GuzzleHttp\RequestOptions::SINK

傳入字符串來指定將要保存響應主體內容的文件的路徑:

$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);

傳入 fopen() 返回的資源將響應寫入PHP流:

$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);

傳入 Psr\Http\Message\StreamInterface 對象將響應寫入打開的PSR-7流。

$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);

ssl_key

  • 摘要

    指定一個鏈接到私有SSL密鑰的PEM格式的文件的路徑的字符串。 如果需要密碼,設置成一個數組,數組第一個元素為鏈接到私有SSL密鑰的PEM格式的文件的路徑,第二個元素為認證密碼。

  • 類型

    stringarray

  • 默認值

    None

  • 常量

    GuzzleHttp\RequestOptions::SSL_KEY

stream

  • 摘要

    設置成 true 流響應,而非下載響應。

  • 類型

    bool

  • 默認值

    false

  • 常量

    GuzzleHttp\RequestOptions::STREAM

$response = $client->request('GET', '/stream/20', ['stream' => true]);
// Read bytes off of the stream until the end of the stream is reached
$body = $response->getBody();
while (!$body->eof()) {
    echo $body->read(1024);
}

synchronous

  • 摘要

    設置成 true 來通知HTTP處理器你要等待響應,這有利於優化。

  • 類型

    bool

  • 默認值

    none

  • 常量

    GuzzleHttp\RequestOptions::SYNCHRONOUS

verify

  • 摘要

    請求時驗證SSL證書行為。設置成 true 啟用SSL證書驗證,默認使用操作系統提供的CA包。設置成 false 禁用證書驗證(這是不安全的!)。設置成字符串啟用驗證,並使用該字符串作為自定義證書CA包的路徑。

  • 類型

    boolstring

  • 默認值

    true

  • 常量

    GuzzleHttp\RequestOptions::VERIFY

// Use the system's CA bundle (this is 默認設置)
$client->request('GET', '/', ['verify' => true]);

// Use a custom SSL certificate on disk.
$client->request('GET', '/', ['verify' => '/path/to/cert.pem']);

// Disable validation entirely (don't do this!).
$client->request('GET', '/', ['verify' => false]);

並非所有的系統磁盤上都存在CA包,比如,Windows和OS X並沒有通用的本地CA包。 當設置"verify" 為 true 時,Guzzle將盡力在你的操作系統中找到合適的CA包, 當使用cURL或PHP 5.6以上版本的流時,Guzzle將按以下順序嘗試查找CA包:

  1. 檢查php.ini文件中是否設置了 openssl.cafile
  2. 檢查php.ini文件中是否設置了 curl.cainfo
  3. 檢查 /etc/pki/tls/certs/ca-bundle.crt 是否存在 (Red Hat, CentOS, Fedora; 由ca-certificates包提供)
  4. 檢查 /etc/ssl/certs/ca-certificates.crt 是否存在 (Ubuntu, Debian; 由ca-certificates包提供)
  5. 檢查 /usr/local/share/certs/ca-root-nss.crt 是否存在 (FreeBSD; 由ca_root_nss包提供)
  6. 檢查 /usr/local/etc/openssl/cert.pem 是否存在 (OS X; 由homebrew提供)
  7. 檢查 C:\windows\system32\curl-ca-bundle.crt 是否存在 (Windows)
  8. 檢查 C:\windows\curl-ca-bundle.crt 是否存在 (Windows)

查詢的結果將緩存在內存中,以便同一進程后續快速調用。 然而在有些服務器如Apache中每個請求都在獨立的進程中,你應該考慮設置 openssl.cafile 環境變量,指定到磁盤文件,以便整個過程都跳過。

如果你不需要特殊的證書包,可以使用Mozilla提供的通用CA包,你可以在 這里 下載(由cURL的維護者提供)。 一旦磁盤有了CA包,你可以設置PHP ini配置文件,指定該文件的路徑到變量 openssl.cafile 中,這樣就可以在請求中省略 "verify" 參數。 你可以在 cURL 網站 發現更多關於SSL證書的細節。

timeout

  • 摘要

    請求超時的秒數。使用 0 無限期的等待(默認行為)。

  • 類型

    float

  • 默認值

    0

  • 常量

    GuzzleHttp\RequestOptions::TIMEOUT

// Timeout if a server does not return a response in 3.14 seconds.
$client->request('GET', '/delay/5', ['timeout' => 3.14]);
// PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\RequestException'

version

  • 摘要

    請求要使用到的協議版本。

  • 類型

    string, float

  • 默認值

    1.1

  • 常量

    GuzzleHttp\RequestOptions::VERSION

// Force HTTP/1.0
$request = $client->request('GET', '/get', ['version' => 1.0]);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM