Laravel 提供了一个简洁而富有表现力的 API,它基于 Guzzle HTTP 客户端,让你能够快速发出传出 HTTP 请求,以便与其他 Web 应用程序进行通信。Laravel 对 Guzzle 的封装专注于其最常见的用例和卓越的开发体验。
要发出请求,您可以使用 head、get、post、put、patch 和 delete 方法 由 Http facade 提供。首先,让我们检查如何向另一个 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 ErrorHTTP 客户端也允许你使用 URI 模板规范 构建请求 URL。为了定义可以由你的 URI 模板展开的 URL 参数,你可以使用 withUrlParameters 方法:
Http::withUrlParameters([
'endpoint' => 'https://laravel.com',
'page' => 'docs',
'version' => '12.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 请求时,你可以直接将查询字符串附加到 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');如果您想使用 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 方法:
// Basic authentication...
$response = Http::withBasicAuth('taylor@laravel.com', 'secret')->post(/* ... */);
// Digest authentication...
$response = Http::withDigestAuth('taylor@laravel.com', 'secret')->post(/* ... */);如果您想快速添加一个承载令牌到请求的 Authorization 头,您可以使用 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 Exception;
use Illuminate\Http\Client\PendingRequest;
$response = Http::retry(3, 100, function (Exception $exception, PendingRequest $request) {
return $exception instanceof ConnectionException;
})->post(/* ... */);如果请求尝试失败,您可能希望在进行新的尝试之前修改该请求. 您可以通过修改传递给您提供给 retry 方法的可调用对象的请求参数来实现这一点. 例如,如果第一次尝试返回了身份验证错误,您可能希望使用新的授权令牌重试该请求:
use Exception;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
$response = Http::withToken($this->getToken())->retry(2, 0, function (Exception $exception, PendingRequest $request) {
if (! $exception instanceof RequestException || $exception->response->status() !== 401) {
return false;
}
$request->withToken($this->getNewToken());
return true;
})->post(/* ... */);如果所有请求都失败,Illuminate\Http\Client\RequestException 的一个实例将被抛出。如果你想禁用此行为,你可以提供一个值为 false 的 throw 参数。禁用后,客户端收到的最后响应将在所有重试尝试后返回:
$response = Http::retry(3, 100, throw: false)->post(/* ... */);[!WARNING]
如果所有请求因为连接问题而失败,仍将抛出Illuminate\Http\Client\ConnectionException,即使throw参数设置为false。
与 Guzzle 的默认行为不同,Laravel 的 HTTP 客户端封装在客户端或服务器错误(服务器返回的 400 和 500 级别响应)时不会抛出异常。你可以使用 successful、clientError 或 serverError 方法来判断是否返回了这些错误之一:
// Determine if the status code is >= 200 and < 300...
$response->successful();
// Determine if the status code is >= 400...
$response->failed();
// Determine if the response has a 400 level status code...
$response->clientError();
// Determine if the response has a 500 level status code...
$response->serverError();
// Immediately execute the given callback if there was a client or server error...
$response->onError(callable $callback);如果您有一个响应实例,并且希望在响应状态码表示客户端或服务器错误时抛出一个 Illuminate\Http\Client\RequestException 实例,您可以使用 throw 或 throwIf 方法:
use Illuminate\Http\Client\Response;
$response = Http::post(/* ... */);
// Throw an exception if a client or server error occurred...
$response->throw();
// Throw an exception if an error occurred and the given condition is true...
$response->throwIf($condition);
// Throw an exception if an error occurred and the given closure resolves to true...
$response->throwIf(fn (Response $response) => true);
// Throw an exception if an error occurred and the given condition is false...
$response->throwUnless($condition);
// Throw an exception if an error occurred and the given closure resolves to false...
$response->throwUnless(fn (Response $response) => false);
// Throw an exception if the response has a specific status code...
$response->throwIfStatus(403);
// Throw an exception unless the response has a specific status code...
$response->throwUnlessStatus(200);
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(); Request or a Request message, including any applicable HTTP headers.
use Illuminate\Http\Client\RequestException;
->registered(function (): void {
// Truncate request exception messages to 240 characters...
RequestException::truncateAt(240);
// Disable request exception message truncation...
RequestException::dontTruncate();
})或者,您可以自定义每个请求的异常截断行为,使用 truncateExceptionsAt 方法:
return Http::truncateExceptionsAt(240)->post(/* ... */);由于 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 方法。 withOptions 方法接受一个键/值对数组 :
$response = Http::withOptions([
'debug' => true,
])->get('http://example.com/users');为了配置每个出站请求的默认选项,您可以使用 globalOptions 方法。通常,此方法应在您应用的 AppServiceProvider 的 boot 方法中调用:
use Illuminate\Support\Facades\Http;
/**
* Bootstrap any application services.
*/
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) {
// The batch has been created but no requests have been initialized...
})->progress(function (Batch $batch, int|string $key, Response $response) {
// An individual request has completed successfully...
})->then(function (Batch $batch, array $results) {
// All requests completed successfully...
})->catch(function (Batch $batch, int|string $key, Response|RequestException|ConnectionException $response) {
// First batch request failure detected...
})->finally(function (Batch $batch, array $results) {
// The batch has finished executing...
})->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 方法启动一个 批次 后,你无法再向其中添加新的请求。尝试这样做将导致抛出 Illuminate\Http\Client\BatchInProgressException 异常。
请求批次的最大并发量可以通过 concurrency 方法来控制。此值决定了在处理请求批次时,可以同时进行的 HTTP 请求的最大数量:
$responses = Http::batch(fn (Batch $batch) => [
// ...
])->concurrency(5)->send();提供给批处理完成回调的 Illuminate\Http\Client\Batch 实例具有多种属性和方法,以协助你与给定请求批次进行交互和检查:
// The number of requests assigned to the batch...
$batch->totalRequests;
// The number of requests that have not been processed yet...
$batch->pendingRequests;
// The number of requests that have failed...
$batch->failedRequests;
// The number of requests that have been processed thus far...
$batch->processedRequests();
// Indicates if the batch has finished executing...
$batch->finished();
// Indicates if the batch has request failures...
$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) {
// All requests completed successfully...
})->defer();Laravel HTTP 客户端允许你定义“宏”,这些宏可以作为一种流畅、富有表现力的机制,用于在与整个应用程序中的服务交互时配置常见的请求路径和请求头。要开始使用,你可以在应用程序的 App\Providers\AppServiceProvider 类的 boot 方法中定义宏:
use Illuminate\Support\Facades\Http;
/**
* Bootstrap any application services.
*/
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(/* ... */);此外,你也可以向 fake 方法传递一个数组。 数组的键应该表示你希望伪造的 URL 模式及其相关的响应。 字符 * 可以用作通配符。 你可以使用 Http 门面的 response 方法来构建这些端点的存根/伪造响应:
Http::fake([
// Stub a JSON response for GitHub endpoints...
'github.com/*' => Http::response(['foo' => 'bar'], 200, $headers),
// Stub a string response for Google endpoints...
'google.com/*' => Http::response('Hello World', 200, $headers),
]);对未被模拟的 URL 发出的任何请求都将被实际执行。如果您希望指定一个回退 URL 模式来模拟所有不匹配的 URL,您可以使用一个单独的 * 字符:
Http::fake([
// Stub a JSON response for GitHub endpoints...
'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),
// Stub a string response for all other endpoints...
'*' => 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。你可以指示 HTTP 客户端抛出连接异常使用 failedConnection 方法:
Http::fake([
'github.com/*' => Http::failedConnection(),
]);为了测试你的应用程序在抛出 Illuminate\Http\Client\RequestException 时的行为,你可以使用 failedRequest 方法:
Http::fake([
'github.com/*' => Http::failedRequest(['code' => 'not_found'], 404),
]);有时你可能需要指定单个 URL 应按照特定顺序返回一系列伪造响应。 你可以通过使用 Http::sequence 方法来构建响应:
Http::fake([
// Stub a series of responses for GitHub endpoints...
'github.com/*' => Http::sequence()
->push('Hello World', 200)
->push(['foo' => 'bar'], 200)
->pushStatus(404),
]);当响应序列中的所有响应都被消耗完时, 任何进一步的请求都将导致响应序列抛出异常。 如果您想指定一个在序列为空时应返回的默认响应, 您可以使用 whenEmpty 方法:
Http::fake([
// Stub a series of responses for GitHub endpoints...
'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'),
]);
// An "ok" response is returned...
Http::get('https://github.com/laravel/framework');
// An exception is thrown...
Http::get('https://laravel.com');有时,您可能希望阻止大多数杂散请求,同时仍然允许特定请求执行。为此,您可以向 allowStrayRequests 方法传递一个 URL 模式数组。任何匹配给定模式之一的请求都将被允许,而所有其他请求将继续抛出异常:
use Illuminate\Support\Facades\Http;
Http::preventStrayRequests();
Http::allowStrayRequests([
'http://127.0.0.1:5000/*',
]);
// This request is executed...
Http::get('http://127.0.0.1:5000/generate');
// An exception is thrown...
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
{
/**
* Handle the event.
*/
public function handle(RequestSending $event): void
{
// $event->request ...
}
}