在PHP中實現(xiàn)使用Guzzle執(zhí)行POST和GET請求
以往在項目中要用到第三方接口時會用到封裝好的curl執(zhí)行請求,現(xiàn)在有了更好的解決方案——Guzzle。
下面是官方介紹:
Guzzle是一個PHP的HTTP客戶端,用來輕而易舉地發(fā)送請求,并集成到我們的WEB服務(wù)上。
接口簡單:構(gòu)建查詢語句、POST請求、分流上傳下載大文件、使用HTTP cookies、上傳JSON數(shù)據(jù)等等。
發(fā)送同步或異步的請求均使用相同的接口。
使用PSR-7接口來請求、響應(yīng)、分流,允許你使用其他兼容的PSR-7類庫與Guzzle共同開發(fā)。
抽象了底層的HTTP傳輸,允許你改變環(huán)境以及其他的代碼,如:對cURL與PHP的流或socket并非重度依賴,非阻塞事件循環(huán)。
中間件系統(tǒng)允許你創(chuàng)建構(gòu)成客戶端行為。
安裝
composer require guzzlehttp/guzzle //用composer安裝最新guzzle,當(dāng)前是6.3版
GET請求示例
$client = new GuzzleHttp\Client(); //初始化客戶端 $response = $client->get('http://httpbin.org/get', [ 'query' => [ //get查詢字符串參數(shù)組 'a' => '參數(shù)a的值', 'b' => '參數(shù)b的值', ], 'timeout' => 3.14 //設(shè)置請求超時時間 ]); // 與上面一條等價 // $response = $client->request('GET','http://httpbin.org/get', [ // 'query' => [ // 'a' => '參數(shù)a的值', // 'b' => '參數(shù)b的值', // ], // 'timeout' => 3.14 // ]); $body = $response->getBody(); //獲取響應(yīng)體,對象 $bodyStr = (string)$body; //對象轉(zhuǎn)字串,這就是請求返回的結(jié)果 echo $bodyStr;
類似的請求方法還有:
$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');
POST請求示例
$client = new GuzzleHttp\Client(); //普通表單`application/x-www-form-urlencoded`的POST請求 $response = $client->post('http://httpbin.org/post', [ 'form_params' => [ //參數(shù)組 'a' => 'aaa', 'b' => 'bbb', 'nested_field' => [ //參數(shù)允許嵌套多層 'A' => 'AAA', 'B' => 'BBB', ] ], ]); //包含文件上傳的表單`multipart/form-data`的POST請求 // $response = $client->post('http://httpbin.org/post', [ // 'multipart' => [ //注意這個參數(shù)組的鍵名與前一個不同 // [ // 'name' => 'a', //字段名 // 'contents' => 'aaa' //對應(yīng)的值 // ], // [ // 'name' => 'upload_file_name', //文件字段名 // 'contents' => fopen('/data/test.md', 'r') //文件資源 // ], // ] // ]); $body = $response->getBody(); //獲取響應(yīng)體,對象 $bodyStr = (string)$body; //對象轉(zhuǎn)字串 echo $bodyStr;
以上便是Guzzle的POST和GET請求的基本介紹,相信很多時間掌握這兩個語法方法已經(jīng)能滿足項目開發(fā)的需求了。當(dāng)然這只是強大的Guzzle功能中很小的一部份,感興趣的同學(xué)想深入了解的可以參考官方文檔。希望大家多多支持腳本之家。
相關(guān)文章
laravel 查詢數(shù)據(jù)庫獲取結(jié)果實現(xiàn)判斷是否為空
今天小編就為大家分享一篇laravel 查詢數(shù)據(jù)庫獲取結(jié)果實現(xiàn)判斷是否為空,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10PHP使用Face++接口開發(fā)微信公眾平臺人臉識別系統(tǒng)的方法
這篇文章主要介紹了PHP使用Face++接口開發(fā)微信公眾平臺人臉識別系統(tǒng)的方法,涉及微信公眾平臺相關(guān)接口的使用技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04Zend Framework實現(xiàn)自定義過濾器的方法
這篇文章主要介紹了Zend Framework實現(xiàn)自定義過濾器的方法,結(jié)合實例形式分析了Zend Framework自定義過濾器的簡單定義與使用方法,需要的朋友可以參考下2016-12-12