PHP项目Laravel HTTP客户端如何用

wen PHP项目 6

本文目录导读:

PHP项目Laravel HTTP客户端如何用

  1. 基础用法
  2. 请求头设置
  3. 超时和重试
  4. 响应处理
  5. 进阶用法
  6. 自定义配置
  7. 错误处理最佳实践
  8. 高级配置
  9. 测试技巧
  10. 性能优化建议

Laravel 的 HTTP 客户端是基于 Guzzle 的封装,提供了简洁优雅的 API 来处理 HTTP 请求,以下是详细的使用指南:

基础用法

发送 GET 请求

use Illuminate\Support\Facades\Http;
// 简单 GET 请求
$response = Http::get('https://api.example.com/users');
// 带查询参数的 GET 请求
$response = Http::get('https://api.example.com/users', [
    'page' => 1,
    'limit' => 10,
    'sort' => 'desc'
]);
// 获取响应数据
$data = $response->json(); // 返回数组
$body = $response->body(); // 返回原始字符串
$status = $response->status(); // 状态码

发送 POST 请求

// 基本 POST 请求
$response = Http::post('https://api.example.com/users', [
    'name' => '张三',
    'email' => 'zhangsan@example.com',
    'password' => 'secret123'
]);
// JSON 格式
$response = Http::post('https://api.example.com/users', [
    'name' => '李四',
    'skills' => ['PHP', 'Laravel', 'JavaScript']
]);

发送 PUT/PATCH/DELETE 请求

// PUT 请求
$response = Http::put('https://api.example.com/users/1', [
    'name' => '更新后的名字'
]);
// PATCH 请求
$response = Http::patch('https://api.example.com/users/1', [
    'name' => '部分更新'
]);
// DELETE 请求
$response = Http::delete('https://api.example.com/users/1');

请求头设置

// 基础认证
$response = Http::withBasicAuth('username', 'password')
    ->get('https://api.example.com/protected');
// Bearer Token
$response = Http::withToken('your-token-here')
    ->get('https://api.example.com/user');
// 自定义请求头
$response = Http::withHeaders([
    'Accept' => 'application/json',
    'X-Custom-Header' => 'Custom Value',
    'User-Agent' => 'Laravel App/1.0'
])->get('https://api.example.com/data');
// 传递 Array 头
$response = Http::withHeaders([
    'Accept-Language' => 'zh-CN',
])->get('https://api.example.com');

超时和重试

// 设置超时时间(秒)
$response = Http::timeout(30)
    ->get('https://api.example.com');
// 连接超时
$response = Http::connectTimeout(5)
    ->get('https://api.example.com');
// 重试配置
$response = Http::retry(3, 100) // 重试次数,延迟毫秒
    ->get('https://api.example.com');

响应处理

$response = Http::get('https://api.example.com/users');
// 检查状态
if ($response->successful()) {
    // 2xx 状态码
}
if ($response->failed()) {
    // 非 2xx 状态码
}
if ($response->clientError()) {
    // 4xx 客户端错误
}
if ($response->serverError()) {
    // 5xx 服务器错误
}
if ($response->status() == 404) {
    // 特定状态码
}
// 获取响应内容
$json = $response->json();  // 数组
$object = $response->object(); // 对象
$collection = $response->collect(); // Collection 实例
$headers = $response->headers(); // 响应头

进阶用法

并发请求

use Illuminate\Http\Client\Pool;
$responses = Http::pool(function (Pool $pool) {
    return [
        $pool->get('https://api.github.com/users/github'),
        $pool->get('https://api.github.com/users/laravel'),
        $pool->post('https://api.example.com/login', [
            'email' => 'test@example.com',
            'password' => 'secret'
        ])
    ];
});
$response1 = $responses[0];
$response2 = $responses[1];
$response3 = $responses[2];

文件上传

use Illuminate\Http\Client\Multipart;
// 常规上传
$response = Http::attach(
    'avatar', 
    file_get_contents('/path/to/image.jpg'), 
    'avatar.jpg'
)->post('https://api.example.com/upload');
// 多文件上传
$response = Http::attach([
    'files' => fopen('/path/to/file1.pdf', 'r'),
    'files2' => fopen('/path/to/file2.pdf', 'r')
])->post('https://api.example.com/upload');

下载文件

$response = Http::get('https://example.com/file.zip');
// 保存到本地
$response->body();
Storage::disk('local')->put('file.zip', $response->body());
// 或者直接流式下载
$response = Http::timeout(300)->get('https://example.com/large-file.zip');
$response->toPsrResponse()->getBody()->getContents();

自定义配置

// 禁用 SSL 验证(仅限开发环境)
$response = Http::withoutVerifying()
    ->get('https://api.example.com');
// 自定义端口
$response = Http::get('https://api.example.com:8080/api');
// 代理设置
$response = Http::withOptions([
    'proxy' => 'http://proxy.example.com:8080',
    'verify' => false
])->get('https://api.example.com');

错误处理最佳实践

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
try {
    $response = Http::timeout(30)
        ->withToken($token)
        ->post('https://api.example.com/export', $data);
    if ($response->successful()) {
        return $response->json();
    }
    // 记录错误
    Log::error('API 调用失败', [
        'url' => 'https://api.example.com/export',
        'status' => $response->status(),
        'response' => $response->body()
    ]);
    return null;
} catch (RequestException $e) {
    Log::error('HTTP 请求异常', [
        'message' => $e->getMessage(),
        'response' => $e->response?->body()
    ]);
    return null;
}

高级配置

使用配置中心

config/services.php 中添加:

'api' => [
    'base_url' => env('API_BASE_URL', 'https://api.example.com'),
    'timeout' => env('API_TIMEOUT', 30),
    'key' => env('API_KEY'),
],

然后在代码中使用:

$response = Http::baseUrl(config('services.api.base_url'))
    ->timeout(config('services.api.timeout'))
    ->withToken(config('services.api.key'))
    ->get('/v1/users');

使用宏定义

AppServiceProviderboot() 方法中:

use Illuminate\Support\Facades\Http;
Http::macro('api', function () {
    return Http::baseUrl(config('services.api.base_url'))
        ->withToken(auth()->user()->api_token ?? '');
});
// 使用方式
$response = Http::api()->get('/user/profile');

测试技巧

use Illuminate\Support\Facades\Http;
// 模拟 HTTP 响应
Http::fake([
    'https://api.github.com/*' => Http::response([
        'name' => 'Laravel',
        'description' => 'PHP framework'
    ], 200),
]);
// 测试代码
$response = Http::get('https://api.github.com/repos/laravel/framework');
$this->assertEquals('Laravel', $response->json()['name']);

性能优化建议

  1. 复用连接:使用 Http::pool() 处理并发请求
  2. 合理设置超时:避免长时间阻塞
  3. 使用连接池:在 config/http.php 中配置
  4. 对响应进行缓存:对于不经常变化的API响应
// 缓存 API 响应
$users = Cache::remember('api-users', 3600, function () {
    return Http::get('https://api.example.com/users')->json();
});

这份指南涵盖了 Laravel HTTP 客户端的大部分常用功能,根据项目需求,可以选择性地使用这些特性来构建强大的 API 集成。

抱歉,评论功能暂时关闭!