PHP 調用外部 HTTP API 是微服務架構、第三方集成、爬蟲的基礎操作。從原生函數到專業 HTTP 客端,選擇合適工具能大幅提升開發效率與系統穩定性。
$url = "https://api.example.com/user?id=123&type=2";
$response = file_get_contents($url);
$data = json_decode($response, true);
allow_url_fopen = On (php.ini)$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $token",
'content' => json_encode(['name' => 'John']),
'timeout' => 10, // 秒
'ignore_errors' => true, // 獲取 4xx/5xx 響應體
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
]
]);
$response = file_get_contents('https://api.example.com/users', false, $context);
$ch = curl_init('https://api.example.com/users');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(['name' => 'John']),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $token,
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch); // HTTP 碼、耗時、證書信息等
curl_close($ch);
composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client([
'base_uri' => 'https://api.example.com/',
'timeout' => 10.0,
'verify' => true, // SSL 驗證
]);
try {
$response = $client->post('users', [
'json' => ['name' => 'John'], // 自動設置 Content-Type + json_encode
'headers' => ['Authorization' => 'Bearer ' . $token],
]);
$statusCode = $response->getStatusCode(); // 201
$data = json_decode($response->getBody()->getContents(), true);
} catch (RequestException $e) {
if ($e->hasResponse()) {
$errorBody = $e->getResponse()->getBody()->getContents();
}
// 記錄日誌、拋出業務異常...
}
| 特性 | 代碼示例 | 場景 |
|---|---|---|
| 並發請求 | $promises = [$client->getAsync(...), $client->postAsync(...)]; $results = Promise\Utils::unwrap($promises); | 聚合多服務數據、批量推送 |
| 中間件/插件 | $stack->push(new RetryMiddleware($retryDecider)); | 自動重試、熔斷、限流、日誌、鏈路追蹤 |
| 流式響應 | $response = $client->request('GET', '/large-file', ['stream' => true]); | 大文件下載、視頻流、避免內存溢出 |
| Cookie 會話 | $jar = new CookieJar(); $client->request(..., ['cookies' => $jar]); | 模擬登錄、保持會話狀態 |
| 異步/協程 | yield $client->getAsync(...) (搭配 amphp/reactphp) | 高併發 I/O 密集型服務 |
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 簡單 GET、內網、無依賴要求 | file_get_contents | 零依賴、一行代碼 |
| 需 POST/Headers/超時/錯誤處理、不想加依賴 | cURL 封裝工具類 | 功能完整、性能好 |
| 項目長期維護、微服務調用、需重試/熔斷/並發/測試 | Guzzle | 生態豐富、PSR-7/18 標準、可測試性強 |
| 高併發異步架構 | Guzzle + amphp / Swoole Hook | 協程調度、萬級併發 |
verify_peer=true,內網可用自簽 CA 束從 file_get_contents 起步,到 Guzzle 成體系,工具升級本質是為了**可靠性、可觀測性、可維護性**。