Laravel内置HTTP客户端基于Guzzle,安装guzzlehttp/guzzle后可通过Http门面发起请求。1. 使用Http::get()、Http::post()等方法发送GET、POST请求,支持查询参数和JSON数据传输;2. 通过withHeaders()设置请求头,withToken()添加Bearer Token认证;3. 支持超时timeout()、连接超时connectTimeout()及重试retry()机制;4. 可用throw()自动处理4xx/5xx错误响应;5. 发送表单数据使用asForm(),文件上传通过attach()实现;6. 可复用配置创建客户端实例,提升代码可读性与维护性。

在 Laravel 7 及以上版本中,Laravel 提供了一个简洁、强大的 HTTP 客户端——GuzzleHttp 的轻量级封装,让你可以轻松发起外部 API 请求。你不需要直接安装 Guzzle,Laravel 已经内置了对它的支持(只需安装 guzzlehttp/guzzle 包即可)。
Laravel 的 HTTP 客户端基于 Guzzle,所以需要先安装它:
composer require guzzlehttp/guzzle
安装完成后就可以使用 Illuminate\Support\Facades\Http 来发起请求。
使用 Http::get() 方法可以轻松获取外部接口数据:
Http::get('https://api.example.com/users')Http::get('...')->body()
Http::get('...')->json()
Http::get('...')->successful()
示例:
$response = Http::get('https://jsonplaceholder.typicode.com/posts/1');
if ($response->successful()) {
$data = $response->json(); // 转为数组
echo $data['title'];
}传入第二个参数作为查询字符串:
$response = Http::get('https://api.example.com/search', [
'q' => 'laravel',
'limit' => 10
]);
// 请求实际访问:/search?q=laravel&limit=10使用 Http::post() 发送数据:
$response = Http::post('https://api.example.com/users', [
'name' => 'John Doe',
'email' => 'john@example.com'
]);
// 获取返回结果
$user = $response->json();支持发送 JSON、表单数据等格式,默认发送的是 JSON。
使用 withHeaders() 添加自定义请求头:
$response = Http::withHeaders([
'X-API-TOKEN' => 'your-token',
'Content-Type' => 'application/json',
])->post('https://api.example.com/data', [
'title' => 'Test'
]);支持 Bearer Token 和 Basic 认证:
Http::withToken('access_token')
Http::withBasicAuth('username', 'password')
例如:
$response = Http::withToken('eyJ...')->get('https://api.example.com/profile');控制请求行为:
Http::timeout(10)
Http::connectTimeout(5)
Http::retry(3, 100)(重试3次,每次间隔100ms)组合使用:
$response = Http::timeout(5)
->retry(2, 100)
->post('https://api.example.com/submit', $data);可以使用 throw() 自动抛出客户端或服务端错误(4xx 或 5xx):
$response = Http::get('https://api.example.com/bad-endpoint');
$response->throw(); // 如果失败会抛出异常
// 或链式调用
$data = Http::get('...')->throw()->json();也可以手动检查状态码:
if ($response->status() === 404) {
// 处理未找到
}默认是 JSON,如果要发送表单数据,使用 asForm():
$response = Http::asForm()->post('https://api.example.com/login', [
'email' => 'user@example.com',
'password' => 'secret'
]);使用 attach() 上传文件:
$response = Http::attach(
'attachment', file_get_contents('photo.jpg'), 'photo.jpg'
)->post('https://api.example.com/upload');也可以传文件路径:
Http::attach('file', fopen('path/to/photo.jpg', 'r'))如果你多次请求同一个服务,可以用 withHeaders + 变量保存配置:
$client = Http::withToken('x')->timeout(5);
$client->get('https://api.example.com/user');
$client->post('https://api.example.com/posts', $data);基本上就这些。Laravel 的 HTTP 客户端设计得非常直观,适合快速集成第三方 API,代码清晰又安全。
以上就是Laravel的HTTP客户端怎么用_Laravel HTTP Client发起API请求教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号