Guzzle, 讓Laravel 在Controller中發出post request
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安裝 Guzzle
| 
					 1  | 
						Composer require guzzlehttp/guzzle  | 
					
步驟二 : 在Controller最前段加入use
| 
					 1  | 
						use GuzzleHttp\Client;  | 
					
步驟三 : 開始使用
| 
					 1 2  | 
						$client = new \GuzzleHttp\Client(); $res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');  | 
					
這時候就已經把request送出去到指定的網址了,而$res變數就是收到來自遠端伺服器的response
如果要發送非同步request可以這樣做
| 
					 1 2 3 4 5  | 
						$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可以使用
| 
					 1 2 3 4 5 6  | 
						$res->getStatusCode(); // 取得狀態,成功是200 $res->getHeaderLine('content-type'); // 取得表頭 ex:'application/json; charset=utf8' echo $res->getBody(); //取得回傳內容  | 
					

首頁 » 技術文章 » Laravel » Guzzle, 讓Laravel 在Controller中發出post request