Guzzle入門教程
Guzzle是一個PHP的HTTP客戶端,用來輕而易舉地發送請求,並集成到我們的WEB服務上。
- 接口簡單:構建查詢語句、POST請求、分流上傳下載大文件、使用HTTP cookies、上傳JSON數據等等。
- 發送同步或異步的請求均使用相同的接口。
- 使用PSR-7接口來請求、響應、分流,允許你使用其他兼容的PSR-7類庫與Guzzle共同開發。
- 抽象了底層的HTTP傳輸,允許你改變環境以及其他的代碼,如:對cURL與PHP的流或socket並非重度依賴,非阻塞事件循環。
- 中間件系統允許你創建構成客戶端行爲。
安裝
Guzzle是一個流行的PHP HTTP客戶端庫,用於發送HTTP請求並處理響應。以下是一個簡單的Guzzle使用示例,包括GET和POST請求:
安裝 Guzzle:
composer require guzzlehttp/guzzle
GET 請求示例:
<?php
require 'vendor/autoload.php'; // 引入Composer自動加載文件
use GuzzleHttp\Client;
// 創建一個Guzzle客戶端實例
$client = new Client();
// 發送一個GET請求到某個API
$response = $client->request('GET', 'https://api.example.com/data');
// 獲取響應的HTTP狀態碼
$status_code = $response->getStatusCode();
echo "Status Code: " . $status_code . PHP_EOL;
// 獲取JSON格式響應體並解碼爲數組
$json_response = json_decode($response->getBody(), true);
print_r($json_response);
POST 請求示例(帶JSON數據):
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
// 創建一個帶有JSON內容的POST請求
$data = [
'key1' => 'value1',
'key2' => 'value2',
];
$client = new Client();
$options = [
RequestOptions::HEADERS => [
'Content-Type' => 'application/json',
],
RequestOptions::JSON => $data,
];
$response = $client->request('POST', 'https://api.example.com/submit', $options);
$status_code = $response->getStatusCode();
echo "Status Code: " . $status_code . PHP_EOL;
// 解析響應體
$json_response = json_decode($response->getBody(), true);
print_r($json_response);
在上述例子中,我們創建了Client
對象,並通過調用request()
方法來發送HTTP請求。對於POST請求,我們設置了請求頭中的Content-Type
爲application/json
,並且將要發送的數據作爲JSON格式放在選項中。
請根據實際API地址替換 https://api.example.com/data
和 https://api.example.com/submit
。同時,請確保你對目標API具有適當的訪問權限。
Demo
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// 發送一個異步請求
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
歡迎關注公-衆-號【TaonyDaily】、留言、評論,一起學習。
Don’t reinvent the wheel, library code is there to help.
文章來源:劉俊濤的博客
若有幫助到您,歡迎點贊、轉發、支持,您的支持是對我堅持最好的肯定(_)