HTTP 客户端

介绍

Laravel 提供了一个简洁、表达力强的 API 封装 Guzzle HTTP 客户端,使你能够快速发起 HTTP 请求与其它 Web 应用进行通信。Laravel 对 Guzzle 的封装专注于其最常见的使用场景,并提供了出色的开发者体验。

发起请求

要发起请求,您可以使用 Http facade 提供的 headgetpostputpatchdelete 方法。首先,让我们看看如何发起一个基本的 GET 请求到另一个 URL:

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。您可以使用 withUrlParameters 方法来定义可以由 URI 模板扩展的 URL 参数:

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

转储请求

如果您希望在请求发送之前转储即将发出的请求实例并终止脚本的执行,您可以在请求定义的开头添加 dd 方法:

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

请求数据

当然,在发起 POSTPUTPATCH 请求时,通常需要向请求中发送附加数据,因此这些方法接受一个数组作为第二个参数。默认情况下,数据将使用 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 方法向请求中添加头部。此方法接受一个键值对数组:

$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',
]);

认证

您可以使用 withBasicAuthwithDigestAuth 方法分别指定基本认证和摘要认证的凭证:

// 基本认证...
$response = Http::withBasicAuth('taylor@laravel.com', 'secret')->post(/* ... */);

// 摘要认证...
$response = Http::withDigestAuth('taylor@laravel.com', 'secret')->post(/* ... */);

Bearer Token

如果您希望快速将 Bearer token 添加到请求的 Authorization 头部,可以使用 withToken 方法:

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

超时

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

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

如果超出了给定的超时时间,将抛出 Illuminate\Http\Client\ConnectionException 异常。

您可以使用 connectTimeout 方法指定连接到服务器时的最大等待时间(单位为秒):

$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 异常。如果您希望禁用此行为,可以为 retry 方法提供一个 throw 参数,并将其设置为 false。禁用后,所有重试尝试完成后,客户端将返回最后一次接收到的响应:

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

如果所有请求因连接问题失败,即使 throw 参数设置为 false,仍然会抛出 Illuminate\Http\Client\ConnectionException 异常。

错误处理

与 Guzzle 的默认行为不同,Laravel 的 HTTP 客户端封装不会在客户端或服务器错误(服务器返回的 400500 级响应)时抛出异常。您可以使用 successfulclientErrorserverError 方法来确定是否返回了这些错误:

// 判断状态码是否在 200 到 300 之间...
$response->successful();

// 判断状态码是否 >= 400...
$response->failed();

// 判断响应是否为 400 级别状态码...
$response->clientError();

// 判断响应是否为 500 级别状态码...
$response->serverError();

// 如果发生客户端或服务器错误,立即执行给定的回调函数...
$response->onError(callable $callback);

抛出异常

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

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);

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 文件中配置应用程序的异常处理行为,使用 truncateRequestExceptionsAtdontTruncateRequestExceptions 方法:

->withExceptions(function (Exceptions $exceptions) {
    // 将请求异常消息截断为 240 个字符...
    $exceptions->truncateRequestExceptionsAt(240);

    // 禁用请求异常消息截断...
    $exceptions->dontTruncateRequestExceptions();
})

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');

全局中间件

有时,您可能希望注册一个适用于每个传出请求和传入响应的中间件。为此,您可以使用 globalRequestMiddlewareglobalResponseMiddleware 方法。通常,这些方法应该在应用程序的 AppServiceProviderboot 方法中调用:

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 方法。通常,这个方法应该在应用程序的 AppServiceProviderboot 方法中调用:

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 方法不能与其它 HTTP 客户端方法(如 withHeadersmiddleware 方法)链式调用。如果您希望对请求池中的请求应用自定义头部或中间件,应该在池中的每个请求上配置这些选项:

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 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 模式,值是对应的响应。* 字符可以用作通配符字符。对未假造的 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,可以使用单个 * 字符:

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(),
]);

假造响应序列

有时,您可能需要指定一个单一的 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 客户端发送的所有请求都已被假造,您可以调用 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');

检查请求

在假造响应时,您可能希望检查客户端收到的请求,以确保您的应用程序发送了正确的数据或头部。您可以通过在调用 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\RequestIlluminate\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\RequestIlluminate\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();
});

事件

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

RequestSendingConnectionFailed 事件都包含一个公共的 $request 属性,您可以使用它来检查 Illuminate\Http\Client\Request 实例。同样,ResponseReceived 事件也包含 $request$response 属性,您可以使用它们来检查 Illuminate\Http\Client\RequestIlluminate\Http\Client\Response 实例。您可以在应用程序中为这些事件创建【事件监听器】:

use Illuminate\Http\Client\Events\RequestSending;

class LogRequest
{
    /**
     * 处理给定的事件。
     */
    public function handle(RequestSending $event): void
    {
        // $event->request ...
    }
}