HTTP 客户端
简介
Laravel 在 Guzzle HTTP 客户端 之上提供了一套富有表现力且精简的 API,让你可以快速发起出站 HTTP 请求,与其他 Web 应用通信。Laravel 对 Guzzle 的封装聚焦于最常见的使用场景,并致力于出色的开发体验。
发起请求
要发起请求,可使用 Http facade 提供的 head、get、post、put、patch 和 delete 方法。首先,我们来看如何向另一个 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 Error
URI 模板
HTTP 客户端还允许你使用 URI 模板规范 构造请求 URL。要定义可由 URI 模板展开的 URL 参数,可使用 withUrlParameters 方法:
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');
请求数据
当然,发起 POST、PUT 和 PATCH 请求时通常需要附带额外数据,因此这些方法接受一个数据数组作为第二个参数。默认情况下,数据会以 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 方法向请求添加头信息。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 与 Digest 身份认证凭据:
// Basic authentication...
$response = Http::withBasicAuth('taylor@laravel.com', 'secret')->post(/* ... */);
// Digest authentication...
$response = Http::withDigestAuth('taylor@laravel.com', 'secret')->post(/* ... */);
Bearer 令牌
若希望快速向请求的 Authorization 头添加 bearer 令牌,可使用 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 实例。若希望禁用此行为,可提供值为 false 的 throw 参数。禁用后,在所有重试都完成后,将返回客户端收到的最后一次响应:
$response = Http::retry(3, 100, throw: false)->post(/* ... */);
WARNING
若所有请求都因连接问题失败,即使将 throw 参数设为 false,仍会抛出 Illuminate\Http\Client\ConnectionException。
错误处理
与 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();
默认情况下,RequestException 消息在记录或报告时会被截断为 120 个字符。若要自定义或禁用此行为,可在 bootstrap/app.php 文件中配置应用的异常处理行为时,使用 truncateRequestExceptionsAt 与 dontTruncateRequestExceptions 方法:
->withExceptions(function (Exceptions $exceptions) {
// Truncate request exception messages to 240 characters...
$exceptions->truncateRequestExceptionsAt(240);
// Disable request exception message truncation...
$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');
全局中间件
有时,你可能希望注册适用于每一个出站请求与入站响应的中间件。为此,可使用 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 方法为出站请求指定额外的 Guzzle 请求选项。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 方法不能与 withHeaders 或 middleware 等其他 HTTP 客户端方法链式调用。若要对池中请求应用自定义头信息或中间件,应在池中的每个请求上分别配置这些选项:
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;
/**
* 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 服务都提供了帮助你轻松、富有表现力地编写测试的功能,HTTP 客户端也不例外。Http facade 的 fake 方法可指示 HTTP 客户端在发起请求时返回桩 / 伪造响应。
伪造响应
例如,若要指示 HTTP 客户端对每个请求都返回空的、状态码为 200 的响应,可无参数调用 fake 方法:
use Illuminate\Support\Facades\Http;
Http::fake();
$response = Http::post(/* ... */);
伪造特定 URL
或者,可向 fake 方法传入一个数组。数组的键应表示你希望伪造的 URL 模式及其关联响应。可使用 * 字符作为通配符。对尚未伪造的 URL 发起的请求将实际执行。可使用 Http facade 的 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,可使用单个 * 字符:
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 时,应用的行为如何。可使用 failedConnection 方法指示 HTTP 客户端抛出连接异常:
Http::fake([
'github.com/*' => Http::failedConnection(),
]);
伪造响应序列
有时你可能需要指定某个 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 客户端发送的所有请求都已被伪造,可调用 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');
检查请求
在伪造响应时,你偶尔可能希望检查客户端收到的请求,以确保应用发送了正确的数据或头信息。可在调用 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();
});事件
Laravel 在发送 HTTP 请求的过程中会触发三个事件。RequestSending 事件在请求发送前触发,ResponseReceived 事件在收到给定请求的响应后触发。若给定请求未收到响应,则触发 ConnectionFailed 事件。
RequestSending 与 ConnectionFailed 事件都包含公共的 $request 属性,可用于检查 Illuminate\Http\Client\Request 实例。同样,ResponseReceived 事件包含 $request 属性以及可用于检查 Illuminate\Http\Client\Response 实例的 $response 属性。你可以在应用中为这些事件创建事件监听器:
use Illuminate\Http\Client\Events\RequestSending;
class LogRequest
{
/**
* Handle the given event.
*/
public function handle(RequestSending $event): void
{
// $event->request ...
}
}