Laravel 使用Guzzle執行HTTP請求

語言: CN / TW / HK

點選進入“PHP開源社群”    

免費獲取進階面試、文件、視訊資源

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 '上傳失敗';

}

}

下載圖片

$client = new \GuzzleHttp\Client();

$response = $client->request('get', $url, ['save_to' => './2222222.jpg', 'headers' => ['referer' => env('APP_URL', 'http://fotophire.wondershare.com')]]);

if ($response->getStatusCode() == 200) {

return true;

}else{

return false;

}

提交表單

傳送 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客戶端,功能非常強大。

攜帶cookie請求

use GuzzleHttp\Client;

use GuzzleHttp\Cookie\CookieJar;


$cookieJar = CookieJar::fromArray([

'PHPSESSID' => 'b68212de1826c64d77b69dc514c2a9cb'

], 'www.devkang.com'); // 此處記得請求域名需要保持跟請求的url host一致,否則不會攜帶此cookie。


$client = new Client([

'cookies' => $cookieJar,

]);

$result = $client->get('http://www.devkang.com/');


print_r($result->getBody()->getContents());

*宣告:本文於網路整理,版權歸原作者所有,如來源資訊有誤或侵犯權益,請聯絡我們刪除或授權事宜。

END

PHP開源社群

掃描關注  進入”PHP資料“

免費獲取進階

面試、文件、視訊資源

點選“檢視原文”獲取更多