↓ 快轉到主要內容
Guzzle, 讓Laravel 在Controller中發出post request
技術文章Laravel

Guzzle, 讓Laravel 在Controller中發出post request

Posted by Alvin Chen on

Guzzle, 讓Laravel 在Controller中發出post request

·435 字·1 分鐘
作者
Alvin Chen
相信寫 Code 可以改變世界

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

參考網址 : https://github.com/guzzle/guzzle

是的,有時候碰到特殊的需求可能必須要透過其他主機或者網址來取得或者發送資料的時候,就必須要在Controller中送出POST或者GET Request

這時候Guzzle 就幫上大忙了,他是模擬了http client來發送request,這樣就能夠順利取得遠端資料,使用方式也很簡單

下面將介紹如何透過Composer 安裝以及使用Guzzle 如果你還沒有碰過Composer,請先閱讀以下文章

Composer 幫PHP套件找一個家

步驟一 : 透過Composer安裝 Guzzle

Composer require guzzlehttp/guzzle

步驟二 : 在Controller最前段加入use

use GuzzleHttp\Client;

步驟三 : 開始使用

$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

這時候就已經把request送出去到指定的網址了,而$res變數就是收到來自遠端伺服器的response

如果要發送非同步request可以這樣做

$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();

另外,github上也提供了幾個function可以使用

$res->getStatusCode();
// 取得狀態,成功是200
$res->getHeaderLine('content-type');
// 取得表頭 ex:'application/json; charset=utf8'
echo $res->getBody();
//取得回傳內容
Guzzle