laravel http Client基于Guzzle,提供简洁api调用外部服务,支持GET、POST等请求,可设置头信息、认证、超时、重试及并发,响应处理方便,适用于各类HTTP交互场景。

Laravel 提供了强大的 HTTP 客户端 —— IlluminateSupportFacadesHttp,它基于 Guzzle 构建,语法简洁,使用方便。通过 Laravel 的 Http Client,你可以轻松地在项目中调用外部 API,无论是获取数据、提交表单,还是处理 jsON 接口都非常高效。
启用 Laravel Http Client
Laravel 7 及以上版本默认集成了 Http Client,无需额外安装。只需在使用的地方引入 Facade:
use IlluminateSupportFacadesHttp;
然后就可以直接使用 Http::get()、Http::post() 等方法发起请求。
常见的调用方式示例
以下是一些典型的外部 API 调用场景:
// GET 请求获取数据 $response = Http::get(‘https://api.example.com/users’); // 携带查询参数 $response = Http::get(‘https://api.example.com/posts’, [ ‘page’ => 1, ‘limit’ => 10 ]); // POST 提交数据 $response = Http::post(‘https://api.example.com/login’, [ ’email’ => ‘user@example.com’, ‘password‘ => ‘secret’ ]); // PUT 更新资源 $response = Http::put(‘https://api.example.com/users/1’, [ ‘name’ => ‘John Doe’ ]); // delete 删除 $response = Http::delete(‘https://api.example.com/users/1’);
设置请求头与认证信息
很多外部 API 需要 Token 认证或自定义 Header,可以使用 withHeaders 或 withToken 方法:
$response = Http::withHeaders([ ‘X-Header’ => ‘Value’, ‘User-Agent’ => ‘MyApp/1.0’ ])->get(‘https://api.example.com/data’); // 添加 Bearer Token $response = Http::withToken(‘your-api-token’)->get(‘https://api.example.com/profile’); // 添加 Content-Type $response = Http::withToken(‘token’)->acceptJson()->post(‘https://api.example.com/data’, $data);
处理响应结果
请求返回的是 PendingRequest 对象,调用后可通过多种方式获取结果:
// 获取响应体内容(字符串) $body = $response->body(); // 解析为 JSON 数组 $data = $response->json(); // 直接获取某个字段 $name = $response->collect(‘users’)->first()[‘name’]; // 获取状态码和是否成功 $status = $response->status(); $success = $response->successful(); // 200-299 返回 true // 失败时抛出异常 $response->throw(); // 自动处理错误状态码
超时、重试与并发请求
你还可以设置请求的超时时间、自动重试机制,甚至并发多个请求:
// 设置超时(毫秒) $response = Http::timeout(30)->get(‘https://api.example.com/data’); // 请求失败时自动重试(最多3次,每次间隔100ms) $response = Http::retry(3, 100)->get(‘https://api.example.com/data’); // 并发多个请求(Laravel 8+) $responses = Http::pool(fn ($pool) => [ $pool->get(‘https://api.github.com/user’), $pool->get(‘https://api.twitter.com/user’), ]);
基本上就这些。Laravel 的 Http Client 让调用外部 API 变得非常直观和安全,配合 try-catch 使用还能更好处理网络异常。不复杂但容易忽略。