HTTP 客户端
简介
Laravel 为 Guzzle HTTP 客户端 提供了一个极具表现力且最小化的 API,让你能够快速发起传出的 HTTP 请求,以与其他 Web 应用程序进行通信。Laravel 对 Guzzle 的封装专注于最常见的用例,并提供极佳的开发者体验。
发起请求
要发起请求,你可以使用 Http 门面(facade)提供的 head、get、post、put、patch 和 delete 方法。首先,让我们看看如何向另一个 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 Required10$response->forbidden() : bool; // 403 Forbidden11$response->notFound() : bool; // 404 Not Found12$response->requestTimeout() : bool; // 408 Request Timeout13$response->conflict() : bool; // 409 Conflict14$response->unprocessableEntity() : bool; // 422 Unprocessable Entity15$response->tooManyRequests() : bool; // 429 Too Many Requests16$response->serverError() : bool; // 500 Internal Server Error
URI 模板
HTTP 客户端还允许你使用 URI 模板规范 来构建请求 URL。若要定义可由 URI 模板扩展的 URL 参数,可以使用 withUrlParameters 方法:
1Http::withUrlParameters([2 'endpoint' => 'https://laravel.net.cn',3 'page' => 'docs',4 'version' => '12.x',5 'topic' => 'validation',6])->get('{+endpoint}/{page}/{version}/{topic}');
调试请求
如果你想在发送请求前输出请求实例并终止脚本执行,可以在请求定义的开头添加 dd 方法:
1return Http::dd()->get('http://example.com');
请求数据
当然,在发起 POST、PUT 和 PATCH 请求时,通常需要随请求发送额外数据,因此这些方法接受一个数组作为第二个参数。默认情况下,数据将使用 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]);
认证
你可以分别使用 withBasicAuth 和 withDigestAuth 方法指定基本认证(basic)和摘要认证(digest)凭据:
1// Basic authentication...3 4// Digest authentication...
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 实例。如果你想禁用此行为,可以提供一个值为 false 的 throw 参数。禁用后,在尝试完所有重试次数后,客户端将返回最后收到的响应:
1$response = Http::retry(3, 100, throw: false)->post(/* ... */);
如果所有请求由于连接问题而失败,即使 throw 参数设置为 false,也会抛出 Illuminate\Http\Client\ConnectionException。
错误处理
与 Guzzle 的默认行为不同,Laravel 的 HTTP 客户端封装不会在客户端或服务器错误(来自服务器的 400 和 500 级别响应)时抛出异常。你可以使用 successful、clientError 或 serverError 方法来判断是否返回了此类错误:
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,可以使用 throw 或 throwIf 方法:
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 文件中配置应用程序的注册行为时,使用 truncateAt 和 dontTruncate 方法:
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');
全局中间件
有时,你可能希望注册一个适用于每个传出请求和传入响应的中间件。为此,你可以使用 globalRequestMiddleware 和 globalResponseMiddleware 方法。通常,这些方法应在应用程序 AppServiceProvider 的 boot 方法中调用:
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 方法。通常,该方法应在应用程序 AppServiceProvider 的 boot 方法中调用:
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 客户端方法(如 withHeaders 或 middleware)链式调用。如果你想对池中的请求应用自定义请求头或中间件,应在池中的每个请求上进行配置:
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\Request 和 Illuminate\Http\Client\Response 的实例:
1Http::fake([ 2 'https://laravel.net.cn' => Http::response(status: 500), 3 'https://nova.laravel.net.cn/' => Http::response(), 4]); 5 6Http::get('https://laravel.net.cn'); 7Http::get('https://nova.laravel.net.cn/'); 8 9$recorded = Http::recorded();10 11[$request, $response] = $recorded[0];
此外,recorded 方法接受一个闭包,该闭包接收 Illuminate\Http\Client\Request 和 Illuminate\Http\Client\Response 的实例,可用于根据你的预期过滤请求/响应对:
1use Illuminate\Http\Client\Request; 2use Illuminate\Http\Client\Response; 3 4Http::fake([ 5 'https://laravel.net.cn' => Http::response(status: 500), 6 'https://nova.laravel.net.cn/' => Http::response(), 7]); 8 9Http::get('https://laravel.net.cn');10Http::get('https://nova.laravel.net.cn/');11 12$recorded = Http::recorded(function (Request $request, Response $response) {13 return $request->url() !== 'https://laravel.net.cn' &&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.net.cn');
有时,你可能希望阻止大多数未伪造的请求,同时允许执行特定的请求。为此,你可以向 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.net.cn');
活动
Laravel 在发送 HTTP 请求的过程中会触发三个事件。RequestSending 事件在请求发送之前触发,而 ResponseReceived 事件在给定请求收到响应后触发。如果给定请求未收到响应,则会触发 ConnectionFailed 事件。
RequestSending 和 ConnectionFailed 事件都包含一个公开的 $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}