简介

Laravel 为 Guzzle HTTP 客户端提供了一套语义化轻量的API,它可以让你快速的发起HTTP请求与其他Web应用程序进行通信。Laravel对Guzzle的常见用例进行了封装以提供良好的开发体验。

创建请求

你可以使用php Http门面提供的php headphp getphp postphp putphp patchphp delete 方法发起请求。首先,让我们看看如何发起一个基本的php GET请求:

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

php get 方法返回一个 php 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->status() : int;
  6. $response->successful() : bool;
  7. $response->redirect(): bool;
  8. $response->failed() : bool;
  9. $response->clientError() : bool;
  10. $response->header($header) : string;
  11. $response->headers() : array;

php Illuminate\Http\Client\Response 对象还实现了 PHP 的 php ArrayAccess 接口,允许你直接在响应上访问 JSON 响应数据:

  1. return 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 参数,可以使用php withUrlParameters方法:

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

打印请求信息
如果要在发送请求之前打印输出请求信息并且结束脚本运行,你应该在创建请求前调用php dd方法:

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

请求数据

大多数情况下,php POSTphp PUTphp PATCH 携带着额外的请求数据是相当常见的。所以,这些方法的第二个参数接受一个包含着请求数据的数组。默认情况下,这些数据会使用php application/json类型随请求发送:

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

GET 请求查询参数
在创建 php GET 请求时,你可以通过直接向 URL 添加查询字符串或是将键值对作为第二个参数传递给 php get 方法:

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

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

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

发送 URL 编码请求
如果你希望使用 php application/x-www-form-urlencoded 作为请求的数据类型,你应该在创建请求前调用 php asForm 方法:

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

发送原始数据(Raw)请求
如果你想使用一个原始请求体发送请求,你可以在创建请求前调用 php withBody 方法。你还可以将数据类型可以通过该方法的第二个参数提供:

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

Multi-Part 请求
如果您希望以 Multi-Part 请求的形式发送文件,应在发起请求之前调用 php 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 流数据:

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

请求头

可以使用 php withHeaders 方法添加请求头, 该方法接受键/值对格式的数组:

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

你可以使用 php accept 方法指定应用程序响应你的请求所需的内容类型

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

为方便起见,您可以使用 php acceptJson 方法快速指定你的应用程序需要 php application/json 内容类型来响应你的请求:

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

php withHeaders方法将请求头项合并到请求的现有请求头中,如果需要,你可以使用 php 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. ]);

认证

你可以分别使用 php withBasicAuthphp withDigestAuth 方法指定基本和摘要身份验证凭据:

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

Bearer 令牌
如果你想要为你的请求快速添加名为 php Authorization 的 Token 令牌请求头,您可以使用 php withToken 方法:

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

超时

你可以使用php timeout方法指定等待响应的最大秒数。默认情况下HTTP客户端将在30秒后超时:

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

如果超过给定的超时时间,将会抛出 php Illuminate\Http\Client\ConnectionException的错误.

你可以使用php connectTimeout方法指定尝试连接服务器时等待的最大秒数:

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

重试

如果你想要 HTTP 客户端在发生客户端或服务器错误时自动重试请求,你可以使用php retry方法。php retry方法接受请求应该尝试的最大次数和 Laravel 在尝试之间应该等待的毫秒数:

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

如果你想要手动计算尝试之间睡眠的毫秒数,你可以将闭包作为第二个参数传递给 php retry方法:

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

为了方便起见,你也可以为php retry方法的第一个参数传入一个数组。这个数组将被用来决定在后续尝试之间睡眠多少毫秒:

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

如果需要的话,你可以传递一个第三个参数给php retry方法。第三个参数应该是一个可调用的,用于决定是否真的应该尝试重试。例如,如果初始请求遇到了php ConnectionException,你可能只希望重试请求:

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

如果一个请求尝试失败了,你可能希望在进行新尝试之前对请求做出改变。你可以通过修改提供给php retry方法闭包的请求参数来实现这一点。例如,如果第一次尝试返回了一个认证错误,你可能希望用一个新的授权令牌重试请求:

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

如果所有的请求都失败了,将会抛出一个php Illuminate\Http\Client\RequestException错误。 如果你想要禁用这种行为,可以把php throw设置为php false。 当禁用时,客户端收到的最后一个响应将在所有重试尝试之后被返回:

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


[!WARNING]
如果所有的请求都因为连接问题失败了,即使把php throw设置为php false,依然会抛出 php Illuminate\Http\Client\ConnectionException错误

错误处理

与 Guzzle 的默认行为不同,Laravel 的 HTTP 客户端包装器在客户端或服务器错误(服务器返回php 4xxphp 5xx状态码)时不会抛出异常。你可以使用php successfulphp clientError或者php serverError方法来确定是否返回了这些错误之一:

  1. // 判断状态码是否 >= 200 且 < 300...
  2. $response->successful();
  3. // 判断状态码是否 >= 400...
  4. $response->failed();
  5. // 判断响状态码是否是 4xx
  6. $response->clientError();
  7. // 判断响状态码是否是 5xx
  8. $response->serverError();
  9. // 如果发生了客户端或服务器错误,立即执行给定的回调...
  10. $response->onError(callable $callback);

抛出异常
如果你有一个响应实例,并希望如果响应状态码指示客户端或服务器错误时抛出一个 php Illuminate\Http\Client\RequestException 实例,你可以使用 php throwphp throwIf 方法:

  1. use Illuminate\Http\Client\Response;
  2. $response = Http::post(/* ... */);
  3. // 如果客户端或服务器错误发生,抛出异常...
  4. $response->throw();
  5. // 如果错误发生并且给定条件为真,抛出异常..
  6. $response->throwIf($condition);
  7. // 如果错误发生并且给定闭包解析为真,抛出异常...
  8. $response->throwIf(fn (Response $response) => true);
  9. // 如果错误发生并且给定条件为假,抛出异常...
  10. $response->throwUnless($condition);
  11. // 如果错误发生并且给定闭包解析为假,抛出异常...
  12. $response->throwUnless(fn (Response $response) => false);
  13. // 如果响应有特定的状态码,抛出异常...
  14. $response->throwIfStatus(403);
  15. // 除非响应有特定的状态码,否则抛出异常...
  16. $response->throwUnlessStatus(200);
  17. return $response['user']['id'];

php Illuminate\Http\Client\RequestException 实例有一个公共的 php $response 属性,该属性允许你检查返回的响应。

如果没有发生错误,php throw 方法会返回响应实例,允许你将其他操作链式调用到 php throw 方法上:

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

如果你想要在抛出异常之前执行一些附加逻辑,你可以传递一个闭包给 php throw 方法。闭包被调用后,异常将自动被抛出,所以你不需要在闭包内重新抛出异常:

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

Guzzle 中间件

由于 Laravel 的 HTTP 客户端由 Guzzle 提供支持,你可以利用 Guzzle 中间件来操作正在进行的请求或检查传入的响应。要操作正在进行的请求,通过 php withRequestMiddleware 方法注册一个 Guzzle 中间件:

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

同样,你可以通过注册 php withResponseMiddleware 方法的中间件来检查传入的 HTTP 响应:

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

全局中间件
有时,你可能希望注册一个适用于每个正在进行的请求和传入响应的中间件。为此,你可以使用 php globalRequestMiddlewarephp globalResponseMiddleware 方法。通常,这些方法应该在你的应用的 php AppServiceProviderphp boot 方法中调用:

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

Guzzle 选项

你可以使用 php withOptions 方法为正在进行的请求指定额外的 Guzzle 请求选项php withOptions 方法接受一个键值对数组:

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

全局选项
要为每个正在进行的请求配置默认选项,你可以使用 php globalOptions 方法。通常,该方法应该从你的应用的 php AppServiceProviderphp boot 方法中调用:

  1. use Illuminate\Support\Facades\Http;
  2. /**
  3. * 启动任何应用服务。
  4. */
  5. public function boot(): void
  6. {
  7. Http::globalOptions([
  8. 'allow_redirects' => false,
  9. ]);
  10. }

并发请求

有时,你可能希望同时进行多个 HTTP 请求。换句话说,你希望同时派发几个请求,而不是顺序地发出请求。这在与慢速 HTTP API 交互时可以带来显著的性能提升。

幸运的是,你可以使用 php pool 方法来实现这一点。php pool 方法接受一个闭包,该闭包接收一个 php Illuminate\Http\Client\Pool 实例,允许你轻松地向请求池添加请求以进行派发:

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

如你所见,每个响应实例都可以根据它被加入池的顺序访问。如果你愿意,可以使用 php as 方法为请求命名,这样可以按名称访问对应的响应:

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

自定义并发请求
php pool 方法不能与其他 HTTP 客户端方法(例如 php withHeadersphp middleware 方法)链式调用。如果你想要将自定义头或中间件应用于池中的请求,应该在池中的每个请求上配置这些选项:

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

Laravel HTTP 客户端允许你定义「宏」,它可以作为一个流畅的、富有表现力的机制来配置常见的请求路径和头信息,当与整个应用中的服务交云时使用。开始使用宏,你可以在应用的 php App\Providers\AppServiceProvider 类的 php boot 方法中定义:

  1. use Illuminate\Support\Facades\Http;
  2. /**
  3. * 启动任何应用服务。
  4. */
  5. public function boot(): void
  6. {
  7. Http::macro('github', function () {
  8. return Http::withHeaders([
  9. 'X-Example' => 'example',
  10. ])->baseUrl('https://github.com');
  11. });
  12. }

一旦你的宏配置好了,你可以在应用中的任何地方调用它来创建一个带有指定配置的待处理请求:

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

测试

许多 Laravel 服务提供了帮助你轻松且有表现力地编写测试的功能,Laravel 的 HTTP 客户端也不例外。php Http facade 的 php fake 方法允许你指导 HTTP 客户端在请求时返回存根 / 虚拟响应。

伪造响应

例如,要指示 HTTP 客户端在每个请求中返回空的 php 200 状态码响应,你可以调用 php fake 方法而不传递参数:

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

伪造特定的 URL
或者,你可以向 php fake 方法传递一个数组。数组的键应该代表你希望伪造的 URL 模式及其关联的响应。php * 字符可用作通配符。对于没有被伪造的 URL 发出的任何请求都会被实际执行。你可以使用 php Http facade 的 php response 方法为这些端点构建存根 / 虚拟响应:

  1. Http::fake([
  2. // 为 GitHub 端点存根一个 JSON 响应...
  3. 'github.com/*' => Http::response(['foo' => 'bar'], 200, $headers),
  4. // 为 Google 端点存根一个字符串响应...
  5. 'google.com/*' => Http::response('Hello World', 200, $headers),
  6. ]);

如果你想指定一个后备 URL 模式来存根所有不匹配的 URL,你可以使用单个 php * 字符:

  1. Http::fake([
  2. // 为 GitHub 端点存根 JSON 响应...
  3. 'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
  4. // 为其他所有端点存根字符串响应...
  5. '*' => Http::response('Hello World', 200, ['Headers']),
  6. ]);

伪造响应序列
有时候,你可能需要为单个 URL 指定其一系列的伪造响应的返回顺序。你可以使用 php Http::sequence 方法来构建响应,以实现这个功能:

  1. Http::fake([
  2. // 存根 GitHub端点的一系列响应...
  3. 'github.com/*' => Http::sequence()
  4. ->push('Hello World', 200)
  5. ->push(['foo' => 'bar'], 200)
  6. ->pushStatus(404),
  7. ]);

当一个响应序列中的所有响应都被消费后,任何进一步的请求都会导致响应序列抛出异常。如果你想指定当序列为空时应该返回的默认响应,你可以使用 php whenEmpty 方法:

  1. Http::fake([
  2. // 为 GitHub 端点存根一系列响应...
  3. 'github.com/*' => Http::sequence()
  4. ->push('Hello World', 200)
  5. ->push(['foo' => 'bar'], 200)
  6. ->whenEmpty(Http::response()),
  7. ]);

如果你想要伪造一个响应序列,但你又期望在伪造的时候无需指定一个特定的 URL 匹配模式,那么你可以使用 php Http::fakeSequence 方法:

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

Fake 回调
如果你需要更复杂的逻辑来确定对某些端点返回什么响应,你可以将一个闭包传递给 php fake 方法。这个闭包将接收一个 php Illuminate\Http\Client\Request 实例并应返回一个响应实例。在你的闭包中,你可以执行任何必要的逻辑来确定返回哪种类型的响应:

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

避免「流浪的」请求

如果你想确保通过 HTTP 客户端发送的所有请求都在你的个别测试或完整测试套件中被模拟过,你可以调用 php preventStrayRequests 方法。调用这个方法后,任何没有相应假响应的请求都会抛出异常,而不是进行实际的 HTTP 请求:

  1. use Illuminate\Support\Facades\Http;
  2. Http::preventStrayRequests();
  3. Http::fake([
  4. 'github.com/*' => Http::response('ok'),
  5. ]);
  6. // 将会返回 OK 响应...
  7. Http::get('https://github.com/laravel/framework');
  8. // 抛出一个异常...
  9. Http::get('https://laravel.com');

检查请求

当你伪造响应时,你可能偶尔希望检查客户端接收到的请求,以确保你的应用程序正在发送正确的数据或头部。你可以在调用 php Http::fake 后通过调用 php Http::assertSent 方法来完成这个操作。

php assertSent 方法接受一个闭包,该闭包会接收一个 php Illuminate\Http\Client\Request 实例,并应返回一个布尔值,表明请求是否符合你的预期。为了使测试通过,至少必须发出一个与给定预期相匹配的请求:

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

如果需要,你可以使用 php assertNotSent 方法来断言特定的请求没有被发送:

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

你可以使用 php assertSentCount 方法来断言在测试期间「发送」的请求数量:

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

或者,你也可以使用 php assertNothingSent 方法来断言在测试期间没有发送任何请求:

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

记录请求和响应
你可以使用 php recorded 方法来收集所有请求及其对应的响应。php recorded 方法返回一个包含 php Illuminate\Http\Client\Requestphp Illuminate\Http\Client\Response 实例的数组集合:

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

此外,php recorded 方法接受一个闭包,该闭包会接收一个 php Illuminate\Http\Client\Request 实例和一个 php Illuminate\Http\Client\Response 实例,并且可以用来根据你的预期过滤请求 / 响应对:

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

事件

在发送 HTTP 请求的过程中,Laravel 会触发三个事件。php RequestSending 事件在请求发送之前触发,而 php ResponseReceived 事件在接收到给定请求的响应后触发。如果没有收到给定请求的响应,则会触发 php ConnectionFailed 事件。

php RequestSendingphp ConnectionFailed 事件都包含一个公共的 php $request 属性,你可以使用它来检查 php Illuminate\Http\Client\Request 实例。同样地,php ResponseReceived 事件包含一个 php $request 属性以及一个 php $response 属性,可用于检查 php Illuminate\Http\Client\Response 实例。你可以为你的应用程序中的这些事件创建事件监听器:

  1. use Illuminate\Http\Client\Events\RequestSending;
  2. class LogRequest
  3. {
  4. /**
  5. * 处理给定的事件。
  6. */
  7. public function handle(RequestSending $event): void
  8. {
  9. // $event->request ...
  10. }
  11. }