天天看點

PHP guzzle異步請求資料,怎麼在PHP中使用Guzzle執行POST和GET請求

怎麼在PHP中使用Guzzle執行POST和GET請求

釋出時間:2021-02-17 08:01:14

來源:億速雲

閱讀:67

作者:Leah

怎麼在PHP中使用Guzzle執行POST和GET請求?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編将為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

Guzzle是一個PHP的HTTP用戶端,用來輕而易舉地發送請求,并內建到我們的WEB服務上。

接口簡單:建構查詢語句、POST請求、分流上傳下載下傳大檔案、使用HTTP cookies、上傳JSON資料等等。

發送同步或異步的請求均使用相同的接口。

使用PSR-7接口來請求、響應、分流,允許你使用其他相容的PSR-7類庫與Guzzle共同開發。

抽象了底層的HTTP傳輸,允許你改變環境以及其他的代碼,如:對cURL與PHP的流或socket并非重度依賴,非阻塞事件循環。

中間件系統允許你建立構成用戶端行為。

安裝composer require guzzlehttp/guzzle //用composer安裝最新guzzle,目前是6.3版

GET請求示例$client = new GuzzleHttp\Client(); //初始化用戶端

$response = $client->get('http://httpbin.org/get', [

'query' => [ //get查詢字元串參數組

'a' => '參數a的值',

'b' => '參數b的值',

],

'timeout' => 3.14 //設定請求逾時時間

]);

//  與上面一條等價

//  $response = $client->request('GET','http://httpbin.org/get', [

//   'query' => [

//    'a' => '參數a的值',

//    'b' => '參數b的值',

//   ],

//   'timeout' => 3.14

//  ]);

$body = $response->getBody(); //擷取響應體,對象

$bodyStr = (string)$body; //對象轉字串,這就是請求傳回的結果

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' => [  //參數組

'a' => 'aaa',

'b' => 'bbb',

'nested_field' => [ //參數允許嵌套多層

'A' => 'AAA',

'B' => 'BBB',

]

],

]);

//包含檔案上傳的表單`multipart/form-data`的POST請求

//  $response = $client->post('http://httpbin.org/post', [

//   'multipart' => [ //注意這個參數組的鍵名與前一個不同

//    [

//     'name' => 'a', //字段名

//     'contents' => 'aaa' //對應的值

//    ],

//    [

//     'name' => 'upload_file_name', //檔案字段名

//     'contents' => fopen('/data/test.md', 'r') //檔案資源

//    ],

//   ]

//  ]);

$body = $response->getBody(); //擷取響應體,對象

$bodyStr = (string)$body; //對象轉字串

echo $bodyStr;

看完上述内容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速雲行業資訊頻道,感謝您對億速雲的支援。