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

Laravel 提供了强大的 HTTP 客户端 —— Illuminate\Support\Facades\Http,它基于 Guzzle 构建,语法简洁,使用方便。通过 Laravel 的 Http Client,你可以轻松地在项目中调用外部 API,无论是获取数据、提交表单,还是处理 JSON 接口都非常高效。
Laravel 7 及以上版本默认集成了 Http Client,无需额外安装。只需在使用的地方引入 Facade:
use Illuminate\Support\Facades\Http;然后就可以直接使用 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 使用还能更好处理网络异常。不复杂但容易忽略。
以上就是Laravel怎么调用外部API_Laravel Http Client客户端使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号