跳轉至內容

HTTP 客戶端

簡介

Laravel 為 Guzzle HTTP 客戶端 提供了一個極具表現力且最小化的 API,讓你能夠快速發起傳出的 HTTP 請求,以與其他 Web 應用程式進行通訊。Laravel 對 Guzzle 的封裝專注於最常見的用例,並提供極佳的開發者體驗。

發起請求

要發起請求,你可以使用 Http 門面(facade)提供的 headgetpostputpatchdelete 方法。首先,讓我們看看如何向另一個 URL 發起基礎的 GET 請求:

1use Illuminate\Support\Facades\Http;
2 
3$response = Http::get('http://example.com');

get 方法返回 Illuminate\Http\Client\Response 的例項,該例項提供了多種用於檢查響應的方法:

1$response->body() : string;
2$response->json($key = null, $default = null) : mixed;
3$response->object() : object;
4$response->collect($key = null) : Illuminate\Support\Collection;
5$response->resource() : resource;
6$response->status() : int;
7$response->successful() : bool;
8$response->redirect(): bool;
9$response->failed() : bool;
10$response->clientError() : bool;
11$response->header($header) : string;
12$response->headers() : array;

Illuminate\Http\Client\Response 物件還實現了 PHP 的 ArrayAccess 介面,允許你直接在響應例項上訪問 JSON 響應資料:

1return Http::get('http://example.com/users/1')['name'];

除了上述響應方法外,還可以使用以下方法來判斷響應是否包含特定的狀態碼:

1$response->ok() : bool; // 200 OK
2$response->created() : bool; // 201 Created
3$response->accepted() : bool; // 202 Accepted
4$response->noContent() : bool; // 204 No Content
5$response->movedPermanently() : bool; // 301 Moved Permanently
6$response->found() : bool; // 302 Found
7$response->badRequest() : bool; // 400 Bad Request
8$response->unauthorized() : bool; // 401 Unauthorized
9$response->paymentRequired() : bool; // 402 Payment Required
10$response->forbidden() : bool; // 403 Forbidden
11$response->notFound() : bool; // 404 Not Found
12$response->requestTimeout() : bool; // 408 Request Timeout
13$response->conflict() : bool; // 409 Conflict
14$response->unprocessableEntity() : bool; // 422 Unprocessable Entity
15$response->tooManyRequests() : bool; // 429 Too Many Requests
16$response->serverError() : bool; // 500 Internal Server Error

URI 模板

HTTP 客戶端還允許你使用 URI 模板規範 來構建請求 URL。若要定義可由 URI 模板擴充套件的 URL 引數,可以使用 withUrlParameters 方法:

1Http::withUrlParameters([
2 'endpoint' => 'https://laravel.com.tw',
3 'page' => 'docs',
4 'version' => '12.x',
5 'topic' => 'validation',
6])->get('{+endpoint}/{page}/{version}/{topic}');

除錯請求

如果你想在傳送請求前輸出請求例項並終止指令碼執行,可以在請求定義的開頭新增 dd 方法:

1return Http::dd()->get('http://example.com');

請求資料

當然,在發起 POSTPUTPATCH 請求時,通常需要隨請求傳送額外資料,因此這些方法接受一個數組作為第二個引數。預設情況下,資料將使用 application/json 內容型別進行傳送。

1use Illuminate\Support\Facades\Http;
2 
3$response = Http::post('http://example.com/users', [
4 'name' => 'Steve',
5 'role' => 'Network Administrator',
6]);

GET 請求查詢引數

在發起 GET 請求時,你可以直接在 URL 後附加查詢字串,或者將鍵/值對陣列作為 get 方法的第二個引數傳遞:

1$response = Http::get('http://example.com/users', [
2 'name' => 'Taylor',
3 'page' => 1,
4]);

或者,也可以使用 withQueryParameters 方法:

1Http::retry(3, 100)->withQueryParameters([
2 'name' => 'Taylor',
3 'page' => 1,
4])->get('http://example.com/users');

傳送表單 URL 編碼請求

如果你希望使用 application/x-www-form-urlencoded 內容型別傳送資料,應在發起請求前呼叫 asForm 方法:

1$response = Http::asForm()->post('http://example.com/users', [
2 'name' => 'Sara',
3 'role' => 'Privacy Consultant',
4]);

傳送原始請求體

如果你需要在發起請求時提供原始請求體,可以使用 withBody 方法。內容型別可以透過該方法的第二個引數指定:

1$response = Http::withBody(
2 base64_encode($photo), 'image/jpeg'
3)->post('http://example.com/photo');

多部分(Multi-Part)請求

如果你希望以多部分請求的形式傳送檔案,應在發起請求前呼叫 attach 方法。該方法接受檔名及其內容。如有需要,你可以提供第三個引數作為檔名,第四個引數用於提供與該檔案關聯的請求頭:

1$response = Http::attach(
2 'attachment', file_get_contents('photo.jpg'), 'photo.jpg', ['Content-Type' => 'image/jpeg']
3)->post('http://example.com/attachments');

除了傳遞檔案的原始內容,你也可以傳遞一個流資源(stream resource):

1$photo = fopen('photo.jpg', 'r');
2 
3$response = Http::attach(
4 'attachment', $photo, 'photo.jpg'
5)->post('http://example.com/attachments');

請求頭

可以使用 withHeaders 方法向請求新增請求頭。該方法接受一個鍵/值對陣列:

1$response = Http::withHeaders([
2 'X-First' => 'foo',
3 'X-Second' => 'bar'
4])->post('http://example.com/users', [
5 'name' => 'Taylor',
6]);

你可以使用 accept 方法來指定應用程式期望的響應內容型別:

1$response = Http::accept('application/json')->get('http://example.com/users');

為方便起見,你可以使用 acceptJson 方法快速指定應用程式期望的響應內容型別為 application/json

1$response = Http::acceptJson()->get('http://example.com/users');

withHeaders 方法會將新請求頭合併到現有請求頭中。如果需要完全替換所有請求頭,可以使用 replaceHeaders 方法:

1$response = Http::withHeaders([
2 'X-Original' => 'foo',
3])->replaceHeaders([
4 'X-Replacement' => 'bar',
5])->post('http://example.com/users', [
6 'name' => 'Taylor',
7]);

認證

你可以分別使用 withBasicAuthwithDigestAuth 方法指定基本認證(basic)和摘要認證(digest)憑據:

1// Basic authentication...
2$response = Http::withBasicAuth('[email protected]', 'secret')->post(/* ... */);
3 
4// Digest authentication...
5$response = Http::withDigestAuth('[email protected]', 'secret')->post(/* ... */);

Bearer 令牌

如果你想快速將 Bearer 令牌新增到請求的 Authorization 頭中,可以使用 withToken 方法:

1$response = Http::withToken('token')->post(/* ... */);

超時

timeout 方法可用於指定等待響應的最大秒數。預設情況下,HTTP 客戶端在 30 秒後超時。

1$response = Http::timeout(3)->get(/* ... */);

如果超過了給定的超時時間,將丟擲 Illuminate\Http\Client\ConnectionException 例項。

你可以使用 connectTimeout 方法指定嘗試連線伺服器時的最大等待秒數。預設值為 10 秒。

1$response = Http::connectTimeout(3)->get(/* ... */);

重試

如果你希望在發生客戶端或伺服器錯誤時 HTTP 客戶端自動重試請求,可以使用 retry 方法。retry 方法接受請求的最大嘗試次數,以及 Laravel 在重試之間應等待的毫秒數:

1$response = Http::retry(3, 100)->post(/* ... */);

如果你想手動計算重試之間的睡眠時間(毫秒),可以將閉包作為 retry 方法的第二個引數傳遞:

1use Exception;
2 
3$response = Http::retry(3, function (int $attempt, Exception $exception) {
4 return $attempt * 100;
5})->post(/* ... */);

為方便起見,你也可以為 retry 方法的第一個引數提供一個數組。該陣列將用於確定後續嘗試之間應等待的毫秒數:

1$response = Http::retry([100, 200])->post(/* ... */);

如有需要,你可以向 retry 方法傳遞第三個引數。該引數應該是一個可呼叫物件(callable),用於確定是否應該執行重試。例如,你可能只想在初始請求遇到 ConnectionException 時才重試:

1use Illuminate\Http\Client\PendingRequest;
2use Throwable;
3 
4$response = Http::retry(3, 100, function (Throwable $exception, PendingRequest $request) {
5 return $exception instanceof ConnectionException;
6})->post(/* ... */);

如果請求嘗試失敗,你可能希望在進行下一次嘗試前對請求進行修改。你可以透過修改傳遞給 retry 方法閉包的 request 引數來實現。例如,如果第一次嘗試返回了認證錯誤,你可能希望攜帶新的授權令牌重試請求:

1use Illuminate\Http\Client\PendingRequest;
2use Illuminate\Http\Client\RequestException;
3use Throwable;
4 
5$response = Http::withToken($this->getToken())->retry(2, 0, function (Throwable $exception, PendingRequest $request) {
6 if (! $exception instanceof RequestException || $exception->response->status() !== 401) {
7 return false;
8 }
9 
10 $request->withToken($this->getNewToken());
11 
12 return true;
13})->post(/* ... */);

如果所有請求嘗試均失敗,將丟擲 Illuminate\Http\Client\RequestException 例項。如果你想停用此行為,可以提供一個值為 falsethrow 引數。停用後,在嘗試完所有重試次數後,客戶端將返回最後收到的響應:

1$response = Http::retry(3, 100, throw: false)->post(/* ... */);

如果所有請求由於連線問題而失敗,即使 throw 引數設定為 false,也會丟擲 Illuminate\Http\Client\ConnectionException

錯誤處理

與 Guzzle 的預設行為不同,Laravel 的 HTTP 客戶端封裝不會在客戶端或伺服器錯誤(來自伺服器的 400500 級別響應)時丟擲異常。你可以使用 successfulclientErrorserverError 方法來判斷是否返回了此類錯誤:

1// Determine if the status code is >= 200 and < 300...
2$response->successful();
3 
4// Determine if the status code is >= 400...
5$response->failed();
6 
7// Determine if the response has a 400 level status code...
8$response->clientError();
9 
10// Determine if the response has a 500 level status code...
11$response->serverError();
12 
13// Immediately execute the given callback if there was a client or server error...
14$response->onError(callable $callback);

丟擲異常

如果你有一個響應例項,並且想在響應狀態碼錶明存在客戶端或伺服器錯誤時丟擲 Illuminate\Http\Client\RequestException,可以使用 throwthrowIf 方法:

1use Illuminate\Http\Client\Response;
2 
3$response = Http::post(/* ... */);
4 
5// Throw an exception if a client or server error occurred...
6$response->throw();
7 
8// Throw an exception if an error occurred and the given condition is true...
9$response->throwIf($condition);
10 
11// Throw an exception if an error occurred and the given closure resolves to true...
12$response->throwIf(fn (Response $response) => true);
13 
14// Throw an exception if an error occurred and the given condition is false...
15$response->throwUnless($condition);
16 
17// Throw an exception if an error occurred and the given closure resolves to false...
18$response->throwUnless(fn (Response $response) => false);
19 
20// Throw an exception if the response has a specific status code...
21$response->throwIfStatus(403);
22 
23// Throw an exception unless the response has a specific status code...
24$response->throwUnlessStatus(200);
25 
26return $response['user']['id'];

Illuminate\Http\Client\RequestException 例項具有一個公開的 $response 屬性,允許你檢查返回的響應。

如果未發生錯誤,throw 方法會返回響應例項,從而允許你在 throw 方法後連結其他操作:

1return Http::post(/* ... */)->throw()->json();

如果你想在丟擲異常前執行某些額外邏輯,可以向 throw 方法傳遞一個閉包。異常將在閉包執行後自動丟擲,因此無需在閉包內手動重新丟擲:

1use Illuminate\Http\Client\Response;
2use Illuminate\Http\Client\RequestException;
3 
4return Http::post(/* ... */)->throw(function (Response $response, RequestException $e) {
5 // ...
6})->json();

預設情況下,RequestException 的訊息在記錄日誌或報告時會被截斷為 120 個字元。若要自定義或停用此行為,可以在 bootstrap/app.php 檔案中配置應用程式的註冊行為時,使用 truncateAtdontTruncate 方法:

1use Illuminate\Http\Client\RequestException;
2 
3->registered(function (): void {
4 // Truncate request exception messages to 240 characters...
5 RequestException::truncateAt(240);
6 
7 // Disable request exception message truncation...
8 RequestException::dontTruncate();
9})

或者,你也可以使用 truncateExceptionsAt 方法針對單個請求自定義異常截斷行為:

1return Http::truncateExceptionsAt(240)->post(/* ... */);

Guzzle 中介軟體

由於 Laravel 的 HTTP 客戶端由 Guzzle 驅動,你可以利用 Guzzle 中介軟體 來操縱傳出的請求或檢查傳入的響應。若要操縱傳出請求,請透過 withRequestMiddleware 方法註冊一個 Guzzle 中介軟體:

1use Illuminate\Support\Facades\Http;
2use Psr\Http\Message\RequestInterface;
3 
4$response = Http::withRequestMiddleware(
5 function (RequestInterface $request) {
6 return $request->withHeader('X-Example', 'Value');
7 }
8)->get('http://example.com');

同樣,你可以透過 withResponseMiddleware 方法註冊中介軟體來檢查傳入的 HTTP 響應:

1use Illuminate\Support\Facades\Http;
2use Psr\Http\Message\ResponseInterface;
3 
4$response = Http::withResponseMiddleware(
5 function (ResponseInterface $response) {
6 $header = $response->getHeader('X-Example');
7 
8 // ...
9 
10 return $response;
11 }
12)->get('http://example.com');

全域性中介軟體

有時,你可能希望註冊一個適用於每個傳出請求和傳入響應的中介軟體。為此,你可以使用 globalRequestMiddlewareglobalResponseMiddleware 方法。通常,這些方法應在應用程式 AppServiceProviderboot 方法中呼叫:

1use Illuminate\Support\Facades\Http;
2 
3Http::globalRequestMiddleware(fn ($request) => $request->withHeader(
4 'User-Agent', 'Example Application/1.0'
5));
6 
7Http::globalResponseMiddleware(fn ($response) => $response->withHeader(
8 'X-Finished-At', now()->toDateTimeString()
9));

Guzzle 選項

你可以使用 withOptions 方法為傳出請求指定額外的 Guzzle 請求選項withOptions 方法接受鍵/值對陣列:

1$response = Http::withOptions([
2 'debug' => true,
3])->get('http://example.com/users');

全域性選項

要為每個傳出請求配置預設選項,可以使用 globalOptions 方法。通常,該方法應在應用程式 AppServiceProviderboot 方法中呼叫:

1use Illuminate\Support\Facades\Http;
2 
3/**
4 * Bootstrap any application services.
5 */
6public function boot(): void
7{
8 Http::globalOptions([
9 'allow_redirects' => false,
10 ]);
11}

併發請求

有時,你可能希望併發發起多個 HTTP 請求。換句話說,你希望多個請求同時發出,而不是順序執行。在與響應緩慢的 HTTP API 互動時,這可以顯著提升效能。

請求池

幸運的是,你可以使用 pool 方法實現這一點。pool 方法接受一個閉包,該閉包接收一個 Illuminate\Http\Client\Pool 例項,讓你能夠輕鬆將請求新增到請求池中進行排程:

1use Illuminate\Http\Client\Pool;
2use Illuminate\Support\Facades\Http;
3 
4$responses = Http::pool(fn (Pool $pool) => [
5 $pool->get('https:///first'),
6 $pool->get('https:///second'),
7 $pool->get('https:///third'),
8]);
9 
10return $responses[0]->ok() &&
11 $responses[1]->ok() &&
12 $responses[2]->ok();

如你所見,每個響應例項都可以根據其新增到池中的順序進行訪問。如果你願意,可以使用 as 方法為請求命名,從而透過名稱訪問對應的響應:

1use Illuminate\Http\Client\Pool;
2use Illuminate\Support\Facades\Http;
3 
4$responses = Http::pool(fn (Pool $pool) => [
5 $pool->as('first')->get('https:///first'),
6 $pool->as('second')->get('https:///second'),
7 $pool->as('third')->get('https:///third'),
8]);
9 
10return $responses['first']->ok();

可以透過向 pool 方法提供 concurrency 引數來控制請求池的最大併發數。該值決定了處理請求池時,最大允許同時進行的 HTTP 請求數:

1$responses = Http::pool(fn (Pool $pool) => [
2 // ...
3], concurrency: 5);

自定義併發請求

pool 方法無法與其他 HTTP 客戶端方法(如 withHeadersmiddleware)鏈式呼叫。如果你想對池中的請求應用自定義請求頭或中介軟體,應在池中的每個請求上進行配置:

1use Illuminate\Http\Client\Pool;
2use Illuminate\Support\Facades\Http;
3 
4$headers = [
5 'X-Example' => 'example',
6];
7 
8$responses = Http::pool(fn (Pool $pool) => [
9 $pool->withHeaders($headers)->get('http://laravel.test/test'),
10 $pool->withHeaders($headers)->get('http://laravel.test/test'),
11 $pool->withHeaders($headers)->get('http://laravel.test/test'),
12]);

請求批處理

在 Laravel 中處理併發請求的另一種方式是使用 batch 方法。與 pool 方法類似,它接受一個閉包,該閉包接收一個 Illuminate\Http\Client\Batch 例項,這不僅允許你輕鬆將請求新增到請求池中進行排程,還允許你定義完成後的回撥:

1use Illuminate\Http\Client\Batch;
2use Illuminate\Http\Client\ConnectionException;
3use Illuminate\Http\Client\RequestException;
4use Illuminate\Http\Client\Response;
5use Illuminate\Support\Facades\Http;
6 
7$responses = Http::batch(fn (Batch $batch) => [
8 $batch->get('https:///first'),
9 $batch->get('https:///second'),
10 $batch->get('https:///third'),
11])->before(function (Batch $batch) {
12 // The batch has been created but no requests have been initialized...
13})->progress(function (Batch $batch, int|string $key, Response $response) {
14 // An individual request has completed successfully...
15})->then(function (Batch $batch, array $results) {
16 // All requests completed successfully...
17})->catch(function (Batch $batch, int|string $key, Response|RequestException|ConnectionException $response) {
18 // Batch request failure detected...
19})->finally(function (Batch $batch, array $results) {
20 // The batch has finished executing...
21})->send();

pool 方法一樣,你可以使用 as 方法來命名你的請求:

1$responses = Http::batch(fn (Batch $batch) => [
2 $batch->as('first')->get('https:///first'),
3 $batch->as('second')->get('https:///second'),
4 $batch->as('third')->get('https:///third'),
5])->send();

在透過呼叫 send 方法啟動 batch 後,將無法再向其中新增新請求。嘗試這樣做會丟擲 Illuminate\Http\Client\BatchInProgressException 異常。

請求批處理的最大併發數可以透過 concurrency 方法進行控制。該值決定了在處理請求批處理時,最大允許同時進行的 HTTP 請求數:

1$responses = Http::batch(fn (Batch $batch) => [
2 // ...
3])->concurrency(5)->send();

檢查批處理

提供給批處理完成回撥的 Illuminate\Http\Client\Batch 例項具有多種屬性和方法,可協助你與給定的請求批處理進行互動並進行檢查:

1// The number of requests assigned to the batch...
2$batch->totalRequests;
3 
4// The number of requests that have not been processed yet...
5$batch->pendingRequests;
6 
7// The number of requests that have failed...
8$batch->failedRequests;
9 
10// The number of requests that have been processed thus far...
11$batch->processedRequests();
12 
13// Indicates if the batch has finished executing...
14$batch->finished();
15 
16// Indicates if the batch has request failures...
17$batch->hasFailures();

延遲批處理

當呼叫 defer 方法時,請求批處理不會立即執行。相反,Laravel 會在當前應用程式請求的 HTTP 響應傳送給使用者之後執行該批處理,從而保持應用程式的快速響應體驗:

1use Illuminate\Http\Client\Batch;
2use Illuminate\Support\Facades\Http;
3 
4$responses = Http::batch(fn (Batch $batch) => [
5 $batch->get('https:///first'),
6 $batch->get('https:///second'),
7 $batch->get('https:///third'),
8])->then(function (Batch $batch, array $results) {
9 // All requests completed successfully...
10})->defer();

Laravel 的 HTTP 客戶端允許你定義“宏”,作為一種流暢、富有表現力的機制,用於在應用程式中與各種服務互動時配置通用的請求路徑和請求頭。若要開始使用,可以在應用程式的 App\Providers\AppServiceProvider 類的 boot 方法中定義宏:

1use Illuminate\Support\Facades\Http;
2 
3/**
4 * Bootstrap any application services.
5 */
6public function boot(): void
7{
8 Http::macro('github', function () {
9 return Http::withHeaders([
10 'X-Example' => 'example',
11 ])->baseUrl('https://github.com');
12 });
13}

一旦配置好宏,你就可以在應用程式的任何地方呼叫它,以建立帶有指定配置的掛起請求:

1$response = Http::github()->get('/');

測試

許多 Laravel 服務提供的功能旨在幫助你輕鬆、富有表現力地編寫測試,Laravel 的 HTTP 客戶端也不例外。Http 門面的 fake 方法允許你指示 HTTP 客戶端在發起請求時返回存根(stubbed)或偽造的響應。

偽造響應

例如,若要指示 HTTP 客戶端對每個請求都返回狀態碼為 200 的空響應,可以不帶引數呼叫 fake 方法:

1use Illuminate\Support\Facades\Http;
2 
3Http::fake();
4 
5$response = Http::post(/* ... */);

偽造特定 URL

或者,你可以向 fake 方法傳遞一個數組。陣列的鍵應代表你希望偽造的 URL 模式,鍵值則為關聯的響應。* 字元可用作萬用字元。你可以使用 Http 門面的 response 方法為這些端點構造存根/偽造響應:

1Http::fake([
2 // Stub a JSON response for GitHub endpoints...
3 'github.com/*' => Http::response(['foo' => 'bar'], 200, $headers),
4 
5 // Stub a string response for Google endpoints...
6 'google.com/*' => Http::response('Hello World', 200, $headers),
7]);

對於未進行偽造的 URL 發起的任何請求,都將實際執行。如果你想指定一個能夠攔截所有未匹配 URL 的回退 URL 模式,可以使用單個 * 字元:

1Http::fake([
2 // Stub a JSON response for GitHub endpoints...
3 'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
4 
5 // Stub a string response for all other endpoints...
6 '*' => Http::response('Hello World', 200, ['Headers']),
7]);

為方便起見,透過提供字串、陣列或整數作為響應,可以生成簡單的字串、JSON 或空響應:

1Http::fake([
2 'google.com/*' => 'Hello World',
3 'github.com/*' => ['foo' => 'bar'],
4 'chatgpt.com/*' => 200,
5]);

偽造異常

有時,你需要測試應用程式在 HTTP 客戶端嘗試發起請求時遇到 Illuminate\Http\Client\ConnectionException 時的行為。你可以使用 failedConnection 方法指示 HTTP 客戶端丟擲連線異常:

1Http::fake([
2 'github.com/*' => Http::failedConnection(),
3]);

若要測試應用程式在丟擲 Illuminate\Http\Client\RequestException 時的行為,可以使用 failedRequest 方法:

1$this->mock(GithubService::class);
2 ->shouldReceive('getUser')
3 ->andThrow(
4 Http::failedRequest(['code' => 'not_found'], 404)
5 );

偽造響應序列

有時你可能需要指定單個 URL 按特定順序返回一系列偽造響應。你可以使用 Http::sequence 方法來構建這些響應:

1Http::fake([
2 // Stub a series of responses for GitHub endpoints...
3 'github.com/*' => Http::sequence()
4 ->push('Hello World', 200)
5 ->push(['foo' => 'bar'], 200)
6 ->pushStatus(404),
7]);

當響應序列中的所有響應都被消耗完後,後續的任何請求都會導致響應序列丟擲異常。如果你想指定當序列為空時應返回的預設響應,可以使用 whenEmpty 方法:

1Http::fake([
2 // Stub a series of responses for GitHub endpoints...
3 'github.com/*' => Http::sequence()
4 ->push('Hello World', 200)
5 ->push(['foo' => 'bar'], 200)
6 ->whenEmpty(Http::response()),
7]);

如果你想偽造一個響應序列,但不需要指定特定 URL 模式,可以使用 Http::fakeSequence 方法:

1Http::fakeSequence()
2 ->push('Hello World', 200)
3 ->whenEmpty(Http::response());

偽造回撥

如果需要更復雜的邏輯來確定對某些端點返回什麼響應,可以將閉包傳遞給 fake 方法。該閉包將接收一個 Illuminate\Http\Client\Request 例項,並應返回一個響應例項。在閉包內,你可以執行任何必要的邏輯來決定返回哪種型別的響應:

1use Illuminate\Http\Client\Request;
2 
3Http::fake(function (Request $request) {
4 return Http::response('Hello World', 200);
5});

檢查請求

偽造響應時,偶爾你可能需要檢查客戶端收到的請求,以確保應用程式傳送了正確的資料或請求頭。可以透過在呼叫 Http::fake 之後呼叫 Http::assertSent 方法來實現:

assertSent 方法接受一個閉包,該閉包接收一個 Illuminate\Http\Client\Request 例項,並應返回一個布林值,表示該請求是否符合你的預期。為了使測試透過,必須至少發起一個符合給定預期的請求:

1use Illuminate\Http\Client\Request;
2use Illuminate\Support\Facades\Http;
3 
4Http::fake();
5 
6Http::withHeaders([
7 'X-First' => 'foo',
8])->post('http://example.com/users', [
9 'name' => 'Taylor',
10 'role' => 'Developer',
11]);
12 
13Http::assertSent(function (Request $request) {
14 return $request->hasHeader('X-First', 'foo') &&
15 $request->url() == 'http://example.com/users' &&
16 $request['name'] == 'Taylor' &&
17 $request['role'] == 'Developer';
18});

如有需要,可以使用 assertNotSent 方法斷言某個特定請求未被髮送:

1use Illuminate\Http\Client\Request;
2use Illuminate\Support\Facades\Http;
3 
4Http::fake();
5 
6Http::post('http://example.com/users', [
7 'name' => 'Taylor',
8 'role' => 'Developer',
9]);
10 
11Http::assertNotSent(function (Request $request) {
12 return $request->url() === 'http://example.com/posts';
13});

你可以使用 assertSentCount 方法來斷言測試期間“傳送”了多少個請求:

1Http::fake();
2 
3Http::assertSentCount(5);

或者,你可以使用 assertNothingSent 方法斷言測試期間沒有傳送任何請求:

1Http::fake();
2 
3Http::assertNothingSent();

記錄請求/響應

你可以使用 recorded 方法收集所有請求及其對應的響應。recorded 方法返回一個數組集合,其中包含 Illuminate\Http\Client\RequestIlluminate\Http\Client\Response 的例項:

1Http::fake([
2 'https://laravel.com.tw' => Http::response(status: 500),
3 'https://nova.laravel.com/' => Http::response(),
4]);
5 
6Http::get('https://laravel.com.tw');
7Http::get('https://nova.laravel.com/');
8 
9$recorded = Http::recorded();
10 
11[$request, $response] = $recorded[0];

此外,recorded 方法接受一個閉包,該閉包接收 Illuminate\Http\Client\RequestIlluminate\Http\Client\Response 的例項,可用於根據你的預期過濾請求/響應對:

1use Illuminate\Http\Client\Request;
2use Illuminate\Http\Client\Response;
3 
4Http::fake([
5 'https://laravel.com.tw' => Http::response(status: 500),
6 'https://nova.laravel.com/' => Http::response(),
7]);
8 
9Http::get('https://laravel.com.tw');
10Http::get('https://nova.laravel.com/');
11 
12$recorded = Http::recorded(function (Request $request, Response $response) {
13 return $request->url() !== 'https://laravel.com.tw' &&
14 $response->successful();
15});

防止未偽造的請求

如果你想確保在單個測試或整個測試套件中,透過 HTTP 客戶端傳送的所有請求都已被偽造,可以呼叫 preventStrayRequests 方法。呼叫此方法後,任何沒有對應偽造響應的請求都將丟擲異常,而不是發起實際的 HTTP 請求:

1use Illuminate\Support\Facades\Http;
2 
3Http::preventStrayRequests();
4 
5Http::fake([
6 'github.com/*' => Http::response('ok'),
7]);
8 
9// An "ok" response is returned...
10Http::get('https://github.com/laravel/framework');
11 
12// An exception is thrown...
13Http::get('https://laravel.com.tw');

有時,你可能希望阻止大多數未偽造的請求,同時允許執行特定的請求。為此,你可以向 allowStrayRequests 方法傳遞一個 URL 模式陣列。任何匹配給定模式之一的請求都將被允許,而所有其他請求將繼續丟擲異常:

1use Illuminate\Support\Facades\Http;
2 
3Http::preventStrayRequests();
4 
5Http::allowStrayRequests([
6 'http://127.0.0.1:5000/*',
7]);
8 
9// This request is executed...
10Http::get('http://127.0.0.1:5000/generate');
11 
12// An exception is thrown...
13Http::get('https://laravel.com.tw');

活動

Laravel 在傳送 HTTP 請求的過程中會觸發三個事件。RequestSending 事件在請求傳送之前觸發,而 ResponseReceived 事件在給定請求收到響應後觸發。如果給定請求未收到響應,則會觸發 ConnectionFailed 事件。

RequestSendingConnectionFailed 事件都包含一個公開的 $request 屬性,你可以使用它來檢查 Illuminate\Http\Client\Request 例項。同樣,ResponseReceived 事件包含一個 $request 屬性以及一個 $response 屬性,可用於檢查 Illuminate\Http\Client\Response 例項。你可以在應用程式內為這些事件建立 事件監聽器

1use Illuminate\Http\Client\Events\RequestSending;
2 
3class LogRequest
4{
5 /**
6 * Handle the event.
7 */
8 public function handle(RequestSending $event): void
9 {
10 // $event->request ...
11 }
12}