HTTP 客戶端
📝 此頁面為 Laravel 官方文檔的繁體中文翻譯。查看原始英文版本
HTTP 客戶端
簡介
Laravel 圍繞 Guzzle HTTP 客戶端提供了一個富有表達力的最小化 API,允許您快速發出外部 HTTP 請求以與其他 Web 應用程式通訊。Laravel 對 Guzzle 的包裝專注於其最常見的用例和優良的開發者體驗。
發出請求
要發出請求,您可以使用 Http 外觀提供的 head、get、post、put、patch 和 delete 方法。首先,讓我們看看如何向另一個 URL 發出基本的 GET 請求:
use Illuminate\Support\Facades\Http;
$response = Http::get('http://example.com');
get 方法返回一個 Illuminate\Http\Client\Response 實例,它提供了多種可用於檢查回應的方法:
$response->body() : string;
$response->json($key = null, $default = null) : mixed;
$response->object() : object;
$response->collect($key = null) : Illuminate\Support\Collection;
$response->resource() : resource;
$response->status() : int;
$response->successful() : bool;
$response->redirect(): bool;
$response->failed() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
Illuminate\Http\Client\Response 物件還實現了 PHP 的 ArrayAccess 介面,允許您直接在回應上存取 JSON 回應資料:
return Http::get('http://example.com/users/1')['name'];
除了上面列出的回應方法外,以下方法可用於判斷回應是否具有特定狀態碼:
$response->ok() : bool; // 200 OK
$response->created() : bool; // 201 Created
$response->accepted() : bool; // 202 Accepted
$response->noContent() : bool; // 204 No Content
$response->movedPermanently() : bool; // 301 Moved Permanently
$response->found() : bool; // 302 Found
$response->badRequest() : bool; // 400 Bad Request
$response->unauthorized() : bool; // 401 Unauthorized
$response->paymentRequired() : bool; // 402 Payment Required
$response->forbidden() : bool; // 403 Forbidden
$response->notFound() : bool; // 404 Not Found
$response->requestTimeout() : bool; // 408 Request Timeout
$response->conflict() : bool; // 409 Conflict
$response->unprocessableEntity() : bool; // 422 Unprocessable Entity
$response->tooManyRequests() : bool; // 429 Too Many Requests
$response->serverError() : bool; // 500 Internal Server Error
URI 範本
HTTP 客戶端還允許您使用 URI 範本規範來建立請求 URL。要定義可由 URI 範本展開的 URL 參數,您可以使用 withUrlParameters 方法:
Http::withUrlParameters([
'endpoint' => 'https://laravel.com',
'page' => 'docs',
'version' => '13.x',
'topic' => 'validation',
])->get('{+endpoint}/{page}/{version}/{topic}');
傾印請求
如果您希望在發出請求之前傾印外部請求實例並終止腳本的執行,可以在請求定義的開頭添加 dd 方法:
return Http::dd()->get('http://example.com');
請求資料
當然,當發出 POST、PUT 和 PATCH 請求時,通常會傳送額外的資料,因此這些方法接受一個資料陣列作為其第二個參數。預設情況下,資料將使用 application/json 內容類型傳送:
use Illuminate\Support\Facades\Http;
$response = Http::post('http://example.com/users', [
'name' => 'Steve',
'role' => 'Network Administrator',
]);
GET 請求查詢參數
發出 GET 請求時,您可以直接將查詢字串附加到 URL,或者將鍵/值對陣列作為第二個參數傳遞給 get 方法:
$response = Http::get('http://example.com/users', [
'name' => 'Taylor',
'page' => 1,
]);
或者,可以使用 withQueryParameters 方法:
Http::retry(3, 100)->withQueryParameters([
'name' => 'Taylor',
'page' => 1,
])->get('http://example.com/users');
發送表單 URL 編碼請求
如果您希望使用 application/x-www-form-urlencoded 內容類型傳送資料,則應在發出請求之前呼叫 asForm 方法:
$response = Http::asForm()->post('http://example.com/users', [
'name' => 'Sara',
'role' => 'Privacy Consultant',
]);
發送原始請求主體
如果您希望在發出請求時提供原始請求主體,可以使用 withBody 方法。內容類型可以透過方法的第二個參數提供:
$response = Http::withBody(
base64_encode($photo), 'image/jpeg'
)->post('http://example.com/photo');
多部分請求
如果您希望將檔案作為多部分請求傳送,則應在發出請求之前呼叫 attach 方法。此方法接受檔案的名稱和內容。如果需要,您可以提供第三個參數,它將被視為檔案的檔名,而第四個參數可用於提供與檔案相關的頁頭:
$response = Http::attach(
'attachment', file_get_contents('photo.jpg'), 'photo.jpg', ['Content-Type' => 'image/jpeg']
)->post('http://example.com/attachments');
與其傳遞檔案的原始內容,您還可以傳遞一個串流資源:
$photo = fopen('photo.jpg', 'r');
$response = Http::attach(
'attachment', $photo, 'photo.jpg'
)->post('http://example.com/attachments');
頁頭
可以使用 withHeaders 方法將頁頭添加到請求。此 withHeaders 方法接受一個鍵/值對陣列:
$response = Http::withHeaders([
'X-First' => 'foo',
'X-Second' => 'bar'
])->post('http://example.com/users', [
'name' => 'Taylor',
]);
您可以使用 accept 方法來指定您的應用程式期望回應請求時使用哪種內容類型:
$response = Http::accept('application/json')->get('http://example.com/users');
為了方便,您可以使用 acceptJson 方法來快速指定您的應用程式期望 application/json 內容類型回應請求:
$response = Http::acceptJson()->get('http://example.com/users');
withHeaders 方法將新頁頭合併到請求的現有頁頭中。如果需要,您可以使用 replaceHeaders 方法完全替換所有頁頭:
$response = Http::withHeaders([
'X-Original' => 'foo',
])->replaceHeaders([
'X-Replacement' => 'bar',
])->post('http://example.com/users', [
'name' => 'Taylor',
]);
認證
您可以分別使用 withBasicAuth 和 withDigestAuth 方法來指定基本認證和摘要認證憑據:
// 基本認證...
$response = Http::withBasicAuth('[email protected]', 'secret')->post(/* ... */);
// 摘要認證...
$response = Http::withDigestAuth('[email protected]', 'secret')->post(/* ... */);
Bearer 令牌
如果您希望快速向請求的 Authorization 頁頭添加一個 bearer 令牌,可以使用 withToken 方法:
$response = Http::withToken('token')->post(/* ... */);
逾時
timeout 方法可用於指定等待回應的最大秒數。預設情況下,HTTP 客戶端將在 30 秒後逾時:
$response = Http::timeout(3)->get(/* ... */);
如果超過給定的逾時時間,將拋出 Illuminate\Http\Client\ConnectionException 的實例。
您可以使用 connectTimeout 方法來指定嘗試連接到伺服器時等待的最大秒數。預設為 10 秒:
$response = Http::connectTimeout(3)->get(/* ... */);
重試
如果您希望 HTTP 客戶端在發生客戶端或伺服器錯誤時自動重試請求,可以使用 retry 方法。retry 方法接受應嘗試請求的最大次數和 Laravel 應在嘗試之間等待的毫秒數:
$response = Http::retry(3, 100)->post(/* ... */);
如果您希望手動計算嘗試之間睡眠的毫秒數,可以將一個閉包作為第二個參數傳遞給 retry 方法:
use Exception;
$response = Http::retry(3, function (int $attempt, Exception $exception) {
return $attempt * 100;
})->post(/* ... */);
為了方便,您還可以向 retry 方法傳遞一個陣列作為第一個參數。此陣列將用於確定後續嘗試之間睡眠的毫秒數:
$response = Http::retry([100, 200])->post(/* ... */);
如果需要,您可以向 retry 方法傳遞第三個參數。第三個參數應該是一個可呼叫物件,用於判斷是否應實際嘗試重試。例如,您可能希望僅在初始請求遇到 ConnectionException 時才重試請求:
use Illuminate\Http\Client\PendingRequest;
use Throwable;
$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
return $exception instanceof ConnectionException;
})->post(/* ... */);
如果請求嘗試失敗,您可能希望在進行新的嘗試之前對請求進行更改。您可以透過修改傳遞給可呼叫物件的請求參數來實現此目的。例如,如果第一次嘗試傳回了認證錯誤,您可能希望使用新的授權令牌重試請求:
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Throwable;
$response = Http::withToken($this->getToken())->retry(2, 0, function (Throwable $exception, PendingRequest $request) {
if (! $exception instanceof RequestException || $exception->response->status() !== 401) {
return false;
}
$request->withToken($this->getNewToken());
return true;
})->post(/* ... */);
如果所有請求都失敗,將拋出 Illuminate\Http\Client\RequestException 的實例。如果您希望禁用此行為,可以向 throw 參數提供 false 值。禁用後,客戶端收到的最後一個回應將在所有重試嘗試後返回:
$response = Http::retry(3, 100, throw: false)->post(/* ... */);
[!WARNING] 如果所有請求都因連接問題而失敗,即使將
throw參數設定為false,也將拋出Illuminate\Http\Client\ConnectionException。
錯誤處理
與 Guzzle 的預設行為不同,Laravel 的 HTTP 客戶端包裝器不會在客戶端或伺服器錯誤(來自伺服器的 400 和 500 級回應)時拋出異常。您可以使用 successful、clientError 或 serverError 方法來判斷是否傳回了這些錯誤之一:
// 判斷狀態碼是否 >= 200 且 < 300...
$response->successful();
// 判斷狀態碼是否 >= 400...
$response->failed();
// 判斷回應是否具有 400 級狀態碼...
$response->clientError();
// 判斷回應是否具有 500 級狀態碼...
$response->serverError();
// 如果有客戶端或伺服器錯誤,則立即執行給定的回呼...
$response->onError(callable $callback);
拋出異常
如果您有一個回應實例,並且希望在回應狀態碼指示客戶端或伺服器錯誤時拋出 Illuminate\Http\Client\RequestException 的實例,可以使用 throw 或 throwIf 方法:
use Illuminate\Http\Client\Response;
$response = Http::post(/* ... */);
// 如果發生客戶端或伺服器錯誤,則拋出異常...
$response->throw();
// 如果發生錯誤且給定條件為 true,則拋出異常...
$response->throwIf($condition);
// 如果發生錯誤且給定閉包解析為 true,則拋出異常...
$response->throwIf(fn (Response $response) => true);
// 如果發生錯誤且給定條件為 false,則拋出異常...
$response->throwUnless($condition);
// 如果發生錯誤且給定閉包解析為 false,則拋出異常...
$response->throwUnless(fn (Response $response) => false);
// 如果回應具有特定狀態碼,則拋出異常...
$response->throwIfStatus(403);
// 除非回應具有特定狀態碼,否則拋出異常...
$response->throwUnlessStatus(200);
// 如果發生伺服器錯誤(狀態 >500),則拋出異常...
$response->throwIfServerError();
// 如果發生客戶端錯誤(狀態 >400 且 <500),則拋出異常...
$response->throwIfClientError();
return $response['user']['id'];
Illuminate\Http\Client\RequestException 實例有一個公共 $response 屬性,允許您檢查返回的回應。
throw 方法在沒有發生錯誤時返回回應實例,允許您將其他操作鏈式呼叫到 throw 方法:
return Http::post(/* ... */)->throw()->json();
如果您希望在拋出異常之前執行一些額外的邏輯,可以將一個閉包傳遞給 throw 方法。異常將在閉包被呼叫後自動拋出,因此您不需要從閉包中重新拋出異常:
use Illuminate\Http\Client\Response;
use Illuminate\Http\Client\RequestException;
return Http::post(/* ... */)->throw(function (Response $response, RequestException $e) {
// ...
})->json();
預設情況下,RequestException 訊息在被記錄或報告時會被截斷為 120 個字元。要自訂或禁用此行為,您可以在 bootstrap/app.php 檔案中配置應用程式的已註冊行為時使用 truncateAt 和 dontTruncate 方法:
use Illuminate\Http\Client\RequestException;
->registered(function (): void {
// 將請求異常訊息截斷為 240 個字元...
RequestException::truncateAt(240);
// 禁用請求異常訊息截斷...
RequestException::dontTruncate();
})
或者,您可以使用 truncateExceptionsAt 方法按請求自訂異常截斷行為:
return Http::truncateExceptionsAt(240)->post(/* ... */);
Guzzle 中介層
由於 Laravel 的 HTTP 客戶端由 Guzzle 驅動,您可以利用 Guzzle 中介層來操作外部請求或檢查傳入回應。要操作外部請求,請透過 withRequestMiddleware 方法註冊一個 Guzzle 中介層:
use Illuminate\Support\Facades\Http;
use Psr\Http\Message\RequestInterface;
$response = Http::withRequestMiddleware(
function (RequestInterface $request) {
return $request->withHeader('X-Example', 'Value');
}
)->get('http://example.com');
同樣,您可以透過 withResponseMiddleware 方法註冊一個中間件來檢查傳入的 HTTP 回應:
use Illuminate\Support\Facades\Http;
use Psr\Http\Message\ResponseInterface;
$response = Http::withResponseMiddleware(
function (ResponseInterface $response) {
$header = $response->getHeader('X-Example');
// ...
return $response;
}
)->get('http://example.com');
全域中介層
有時,您可能希望註冊一個應用於每個外部請求和傳入回應的中介層。為此,您可以使用 globalRequestMiddleware 和 globalResponseMiddleware 方法。通常,這些方法應在應用程式的 AppServiceProvider 的 boot 方法中被呼叫:
use Illuminate\Support\Facades\Http;
Http::globalRequestMiddleware(fn ($request) => $request->withHeader(
'User-Agent', 'Example Application/1.0'
));
Http::globalResponseMiddleware(fn ($response) => $response->withHeader(
'X-Finished-At', now()->toDateTimeString()
));
Guzzle 選項
您可以使用 withOptions 方法為外部請求指定額外的 Guzzle 請求選項。withOptions 方法接受一個鍵/值對陣列:
$response = Http::withOptions([
'debug' => true,
])->get('http://example.com/users');
全域選項
要配置每個外部請求的預設選項,您可以使用 globalOptions 方法。通常,此方法應從應用程式的 AppServiceProvider 的 boot 方法中被呼叫:
use Illuminate\Support\Facades\Http;
/**
* 啟動任何應用程式服務。
*/
public function boot(): void
{
Http::globalOptions([
'allow_redirects' => false,
]);
}
並發請求
有時,您可能希望並發發出多個 HTTP 請求。換句話說,您希望同時派發多個請求,而不是按順序發出請求。這可以在與緩慢的 HTTP API 互動時帶來顯著的效能提升。
請求池
幸運的是,您可以使用 pool 方法來實現這一點。pool 方法接受一個閉包,該閉包接收一個 Illuminate\Http\Client\Pool 實例,允許您輕鬆地將請求添加到請求池中以便派發:
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
$responses = Http::pool(fn (Pool $pool) => [
$pool->get('http://localhost/first'),
$pool->get('http://localhost/second'),
$pool->get('http://localhost/third'),
]);
return $responses[0]->ok() &&
$responses[1]->ok() &&
$responses[2]->ok();
如您所見,每個回應實例都可以根據其添加到池中的順序來存取。如果您願意,可以使用 as 方法為請求命名,這允許您按名稱存取相應的回應:
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
$responses = Http::pool(fn (Pool $pool) => [
$pool->as('first')->get('http://localhost/first'),
$pool->as('second')->get('http://localhost/second'),
$pool->as('third')->get('http://localhost/third'),
]);
return $responses['first']->ok();
請求池的最大並發數可以透過向 pool 方法提供 concurrency 參數來控制。此值決定了在處理請求池時可以並發執行的 HTTP 請求的最大數量:
$responses = Http::pool(fn (Pool $pool) => [
// ...
], concurrency: 5);
自訂並發請求
pool 方法不能與其他 HTTP 客戶端方法(例如 withHeaders 或 middleware 方法)鏈式呼叫。如果您希望向池化請求應用自訂頁頭或中介層,則應在池中的每個請求上配置這些選項:
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
$headers = [
'X-Example' => 'example',
];
$responses = Http::pool(fn (Pool $pool) => [
$pool->withHeaders($headers)->get('http://laravel.test/test'),
$pool->withHeaders($headers)->get('http://laravel.test/test'),
$pool->withHeaders($headers)->get('http://laravel.test/test'),
]);
請求批次
在 Laravel 中處理並發請求的另一種方式是使用 batch 方法。像 pool 方法一樣,它接受一個閉包,該閉包接收一個 Illuminate\Http\Client\Batch 實例,允許您輕鬆地將請求添加到請求池中以便派發,但它還允許您定義完成回呼:
use Illuminate\Http\Client\Batch;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
$responses = Http::batch(fn (Batch $batch) => [
$batch->get('http://localhost/first'),
$batch->get('http://localhost/second'),
$batch->get('http://localhost/third'),
])->before(function (Batch $batch) {
// 批次已建立但尚未初始化任何請求...
})->progress(function (Batch $batch, int|string $key, Response $response) {
// 單個請求已成功完成...
})->then(function (Batch $batch, array $results) {
// 所有請求都成功完成了...
})->catch(function (Batch $batch, int|string $key, Response|RequestException|ConnectionException $response) {
// 檢測到批次請求失敗...
})->finally(function (Batch $batch, array $results) {
// 批次已完成執行...
})->send();
像 pool 方法一樣,您可以使用 as 方法來命名您的請求:
$responses = Http::batch(fn (Batch $batch) => [
$batch->as('first')->get('http://localhost/first'),
$batch->as('second')->get('http://localhost/second'),
$batch->as('third')->get('http://localhost/third'),
])->send();
呼叫 send 方法啟動 batch 後,您無法向其添加新嘗試。嘗試這樣做將導致拋出 Illuminate\Http\Client\BatchInProgressException 異常。
請求批次的最大並發數可以透過 concurrency 方法來控制。此值決定了在處理請求批次時可以並發執行的 HTTP 請求的最大數量:
$responses = Http::batch(fn (Batch $batch) => [
// ...
])->concurrency(5)->send();
檢查批次
提供給批次完成回呼的 Illuminate\Http\Client\Batch 實例具有多種屬性和方法,可協助您與給定的請求批次互動並檢查它:
// 分配給批次的請求數量...
$batch->totalRequests;
// 尚未處理的請求數量...
$batch->pendingRequests;
// 已失敗的請求數量...
$batch->failedRequests;
// 截至目前為止已處理的請求數量...
$batch->processedRequests();
// 指示批次是否已完成執行...
$batch->finished();
// 指示批次是否有請求失敗...
$batch->hasFailures();
延遲批次
當呼叫 defer 方法時,請求批次不會立即執行。相反,Laravel 將在當前應用程式請求的 HTTP 回應發送給使用者後執行該批次,使您的應用程式保持快速和回應迅速:
use Illuminate\Http\Client\Batch;
use Illuminate\Support\Facades\Http;
$responses = Http::batch(fn (Batch $batch) => [
$batch->get('http://localhost/first'),
$batch->get('http://localhost/second'),
$batch->get('http://localhost/third'),
])->then(function (Batch $batch, array $results) {
// 所有請求都成功完成了...
})->defer();
巨集
Laravel HTTP 客戶端允許您定義「巨集」,它可以作為一種流暢、富有表達力的機制,用於在與應用程式中的服務互動時配置常見的請求路徑和頁頭。首先,您可以在應用程式的 App\Providers\AppServiceProvider 類別的 boot 方法中定義巨集:
use Illuminate\Support\Facades\Http;
/**
* 啟動任何應用程式服務。
*/
public function boot(): void
{
Http::macro('github', function () {
return Http::withHeaders([
'X-Example' => 'example',
])->baseUrl('https://github.com');
});
}
配置好巨集後,您可以從應用程式中的任何地方呼叫它來建立一個具有指定配置的待處理請求:
$response = Http::github()->get('/');
測試
許多 Laravel 服務提供功能來幫助您輕鬆且富有表達力地編寫測試,Laravel 的 HTTP 客戶端也不例外。Http 外觀的 fake 方法允許您指示 HTTP 客戶端在發出請求時返回存根/虛擬回應。
偽造回應
例如,要指示 HTTP 客戶端對每個請求傳回空的 200 狀態碼回應,您可以不帶參數地呼叫 fake 方法:
use Illuminate\Support\Facades\Http;
Http::fake();
$response = Http::post(/* ... */);
偽造特定 URL
或者,您可以向 fake 方法傳遞一個陣列。陣列的鍵應代表您希望偽造的 URL 模式及其關聯的回應。* 字元可用作萬用字元。您可以使用 Http 外觀的 response 方法來為這些端點建立存根/偽造回應:
Http::fake([
// 為 GitHub 端點偽造 JSON 回應...
'github.com/*' => Http::response(['foo' => 'bar'], 200, $headers),
// 為 Google 端點偽造字串回應...
'google.com/*' => Http::response('Hello World', 200, $headers),
]);
對未偽造的 URL 發出的任何請求都將實際執行。如果您希望指定一個用於偽造所有不匹配 URL 的後備 URL 模式,可以使用單個 * 字元:
Http::fake([
// 為 GitHub 端點偽造 JSON 回應...
'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
// 為所有其他端點偽造字串回應...
'*' => Http::response('Hello World', 200, ['Headers']),
]);
為了方便,可以透過提供字串、陣列或整數作為回應來生成簡單的字串、JSON 和空回應:
Http::fake([
'google.com/*' => 'Hello World',
'github.com/*' => ['foo' => 'bar'],
'chatgpt.com/*' => 200,
]);
偽造異常
有時您可能需要測試如果 HTTP 客戶端在嘗試發出請求時遇到 Illuminate\Http\Client\ConnectionException,您的應用程式的行為。您可以使用 failedConnection 方法指示 HTTP 客戶端拋出連接異常:
Http::fake([
'github.com/*' => Http::failedConnection(),
]);
要測試如果拋出 Illuminate\Http\Client\RequestException,您的應用程式的行為,您可以使用 failedRequest 方法:
$this->mock(GithubService::class);
->shouldReceive('getUser')
->andThrow(
Http::failedRequest(['code' => 'not_found'], 404)
);
偽造回應序列
有時您可能需要指定單個 URL 應按特定順序返回一系列偽造回應。您可以使用 Http::sequence 方法來建立回應來實現這一點:
Http::fake([
// 為 GitHub 端點偽造一系列回應...
'github.com/*' => Http::sequence()
->push('Hello World', 200)
->push(['foo' => 'bar'], 200)
->pushStatus(404),
]);
當回應序列中的所有回應都已被消耗時,任何進一步的請求都將導致回應序列拋出異常。如果您希望指定在序列為空時應返回的預設回應,可以使用 whenEmpty 方法:
Http::fake([
// 為 GitHub 端點偽造一系列回應...
'github.com/*' => Http::sequence()
->push('Hello World', 200)
->push(['foo' => 'bar'], 200)
->whenEmpty(Http::response()),
]);
如果您希望偽造一系列回應但不需要指定應偽造的特定 URL 模式,可以使用 Http::fakeSequence 方法:
Http::fakeSequence()
->push('Hello World', 200)
->whenEmpty(Http::response());
偽造回呼
如果您需要更複雜的邏輯來判斷為特定端點返回什麼回應,可以將一個閉包傳遞給 fake 方法。此閉包將接收 Illuminate\Http\Client\Request 的實例,並應返回一個回應實例。在閉包內,您可以執行必要的邏輯來判斷返回什麼類型的回應:
use Illuminate\Http\Client\Request;
Http::fake(function (Request $request) {
return Http::response('Hello World', 200);
});
檢查請求
偽造回應時,您可能偶爾希望檢查客戶端收到的請求,以確保您的應用程式傳送了正確的資料或頁頭。您可以透過在呼叫 Http::fake 後呼叫 Http::assertSent 方法來實現這一點。
assertSent 方法接受一個閉包,該閉包將接收一個 Illuminate\Http\Client\Request 實例,並應返回一個布林值,指示請求是否符合您的期望。為了使測試通過,必須至少發出一個符合給定期望的請求:
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
Http::fake();
Http::withHeaders([
'X-First' => 'foo',
])->post('http://example.com/users', [
'name' => 'Taylor',
'role' => 'Developer',
]);
Http::assertSent(function (Request $request) {
return $request->hasHeader('X-First', 'foo') &&
$request->url() == 'http://example.com/users' &&
$request['name'] == 'Taylor' &&
$request['role'] == 'Developer';
});
如果需要,您可以使用 assertNotSent 方法斷言未傳送特定請求:
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
Http::fake();
Http::post('http://example.com/users', [
'name' => 'Taylor',
'role' => 'Developer',
]);
Http::assertNotSent(function (Request $request) {
return $request->url() === 'http://example.com/posts';
});
您可以使用 assertSentCount 方法來斷言在測試期間「傳送」了多少個請求:
Http::fake();
Http::assertSentCount(5);
或者,您可以使用 assertNothingSent 方法來斷言在測試期間沒有傳送任何請求:
Http::fake();
Http::assertNothingSent();
記錄請求/回應
您可以使用 recorded 方法來收集所有請求及其相應的回應。recorded 方法返回一個包含 Illuminate\Http\Client\Request 和 Illuminate\Http\Client\Response 實例的陣列集合:
Http::fake([
'https://laravel.com' => Http::response(status: 500),
'https://nova.laravel.com/' => Http::response(),
]);
Http::get('https://laravel.com');
Http::get('https://nova.laravel.com/');
$recorded = Http::recorded();
[$request, $response] = $recorded[0];
此外,recorded 方法接受一個閉包,該閉包將接收 Illuminate\Http\Client\Request 和 Illuminate\Http\Client\Response 的實例,可用於根據您的期望篩選請求/回應對:
use Illuminate\Http\Client\Request;
use Illuminate\Http\Client\Response;
Http::fake([
'https://laravel.com' => Http::response(status: 500),
'https://nova.laravel.com/' => Http::response(),
]);
Http::get('https://laravel.com');
Http::get('https://nova.laravel.com/');
$recorded = Http::recorded(function (Request $request, Response $response) {
return $request->url() !== 'https://laravel.com' &&
$response->successful();
});
防止雜散請求
如果您希望確保透過 HTTP 客戶端傳送的所有請求在單個測試或完整測試套件中都被偽造,可以呼叫 preventStrayRequests 方法。呼叫此方法後,任何沒有相應偽造回應的請求都將拋出異常,而不是發出實際的 HTTP 請求:
use Illuminate\Support\Facades\Http;
Http::preventStrayRequests();
Http::fake([
'github.com/*' => Http::response('ok'),
]);
// 返回 "ok" 回應...
Http::get('https://github.com/laravel/framework');
// 拋出異常...
Http::get('https://laravel.com');
有時,您可能希望防止大多數雜散請求,同時仍允許特定請求執行。為此,您可以向 allowStrayRequests 方法傳遞一個 URL 模式陣列。匹配給定模式之一的任何請求都將被允許,而所有其他請求將繼續拋出異常:
use Illuminate\Support\Facades\Http;
Http::preventStrayRequests();
Http::allowStrayRequests([
'http://127.0.0.1:5000/*',
]);
// 此請求被執行...
Http::get('http://127.0.0.1:5000/generate');
// 拋出異常...
Http::get('https://laravel.com');
事件
Laravel 在發送 HTTP 請求的過程中觸發三個事件。RequestSending 事件在請求被發送之前觸發,而 ResponseReceived 事件在收到給定請求的回應後觸發。如果沒有收到給定請求的回應,則觸發 ConnectionFailed 事件。
RequestSending 和 ConnectionFailed 事件都包含一個公共 $request 屬性,您可以用來檢查 Illuminate\Http\Client\Request 實例。同樣,ResponseReceived 事件包含一個 $request 屬性和一個 $response 屬性,可用於檢查 Illuminate\Http\Client\Response 實例。您可以在應用程式中為這些事件建立事件監聽器:
use Illuminate\Http\Client\Events\RequestSending;
class LogRequest
{
/**
* 處理事件。
*/
public function handle(RequestSending $event): void
{
// $event->request ...
}
}