手冊地址:http://docs.guzzlephp.org/en/stable/request-options.html#headers
Guzzle是一個 PHP 的HTTP客戶端,用來輕而易舉地發送請求,並集成到我們的WEB服務上。Guzzle提供了簡單的接口,構建查詢語句、POST請求、分流上傳下載大文件、使用HTTP cookies、上傳 JSON 數據等等。
安裝
使用Composer安裝:
composer require guzzlehttp/guzzle
或者編輯項目的composer.json文件,添加Guzzle作爲依賴:
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
然後執行 composer update
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');
設置查詢字符串
$response = $client->request('GET', 'http://httpbin.org?foo=bar');
或使用 query
請求參數來聲明查詢字符串參數:
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
使用響應
獲取狀態碼:
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
判斷頭部信息:
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}
獲取返回的頭部信息:
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();
可以將返回體轉換成字符串或者直接以字符串形式讀取:
$stringBody = (string) $body;
$content = $body->getContents();
上傳文件
有時我們需要將文件傳送到另一個web服務上去,可以使用post文件流形式將文件數據傳送到指定web目錄。
$filename = 'a.jpg';
$data = fopen($filename, 'r');
$res = $client->request('POST', 'http://localhost:9999/upload.php', ['body' => $data]);
$body = $res->getBody();
print_r($body->getContents());
接收上傳文件的upload.php可以這樣寫:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = file_get_contents('php://input');
$file = file_put_contents('b.jpg', $data);
if (FALSE === $file) {
echo '上傳成功';
} else {
echo '上傳失敗';
}
}
提交表單
發送 application/x-www-form-urlencoded
POST請求需要你傳入 form_params
數組參數,數組內指定POST的字段。
$res = $client->request('POST', 'http://localhost:9999/form.php', [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
$body = $res->getBody();
print_r((string)$body);
在接收端form.php使用 $_POST
即可獲取上傳的表單數據。
提交JSON數據
有時候我們在於API接口交互的時候需要將數據以特定的json格式傳給api,可以這樣寫:
$res = $client->request('POST', 'http://localhost:9999/json.php', [
'json' => ['foo' => 'bar']
]);
$body = $res->getBody();
print_r((string)$body);
接收端json.php使用 file_get_contents('php://input')
可獲得提交的json數據。
使用Guzzle還可以發送異步請求以及併發請求,具體使用方法可參照 Guzzle官方文檔 。
其實我們在一些特殊場景下可以使用Swoole的協程特性實現異步的http客戶端,功能非常強大。