在 Laravel 中,HTTP 客户端提供了一种简洁而强大的方式来发送 HTTP 请求到其他服务或 API。Laravel 的 HTTP 客户端基于 Guzzle HTTP 客户端构建,提供了流畅的 API 来处理各种 HTTP 请求。以下是一个详细的 Laravel HTTP 客户端教程:
如果你还没有安装 Laravel,可以使用 Composer 来创建一个新的 Laravel 项目:
composer create-project --prefer-dist laravel/laravel myproject
cd myproject
以下是一个使用 Laravel HTTP 客户端发送基本 GET 请求的示例:
use Illuminate\Support\Facades\Http;
Route::get('/fetch-data', function () {
$response = Http::get('https://jsonplaceholder.typicode.com/posts/1');
if ($response->successful()) {
return $response->json();
} else {
return 'Request failed with status code: '.$response->status();
}
});
在这个示例中,我们使用 Http::get
方法发送一个 GET 请求到 https://jsonplaceholder.typicode.com/posts/1
。如果请求成功,我们使用 $response->json()
方法将响应内容解析为 JSON 数组并返回;否则,我们返回请求失败的状态码。
如果你需要在 GET 请求中传递参数,可以将参数作为第二个参数传递给 get
方法:
use Illuminate\Support\Facades\Http;
Route::get('/fetch-data-with-params', function () {
$params = [
'userId' => 1
];
$response = Http::get('https://jsonplaceholder.typicode.com/posts', $params);
if ($response->successful()) {
return $response->json();
} else {
return 'Request failed with status code: '.$response->status();
}
});
在这个示例中,我们将 userId
参数传递给 https://jsonplaceholder.typicode.com/posts
API。
以下是一个使用 Laravel HTTP 客户端发送 POST 请求的示例:
use Illuminate\Support\Facades\Http;
Route::post('/send-data', function () {
$data = [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
];
$response = Http::post('https://jsonplaceholder.typicode.com/posts', $data);
if ($response->successful()) {
return $response->json();
} else {
return 'Request failed with status code: '.$response->status();
}
});
在这个示例中,我们使用 Http::post
方法发送一个 POST 请求到 https://jsonplaceholder.typicode.com/posts
,并传递一个包含 title
、body
和 userId
的数组作为请求数据。
如果你需要在请求中设置自定义的请求头,可以使用 withHeaders
方法:
use Illuminate\Support\Facades\Http;
Route::get('/fetch-data-with-headers', function () {
$response = Http::withHeaders([
'Authorization' => 'Bearer your_token',
'Accept' => 'application/json'
])->get('https://jsonplaceholder.typicode.com/posts/1');
if ($response->successful()) {
return $response->json();
} else {
return 'Request failed with status code: '.$response->status();
}
});
在这个示例中,我们使用 withHeaders
方法设置了 Authorization
和 Accept
请求头。
Laravel HTTP 客户端提供了一些有用的方法来处理响应:
$response->successful()
:检查响应状态码是否在 200-299 范围内。$response->failed()
:检查响应状态码是否不在 200-299 范围内。$response->serverError()
:检查响应状态码是否在 500-599 范围内。$response->clientError()
:检查响应状态码是否在 400-499 范围内。$response->json()
:将响应内容解析为 JSON 数组。$response->body()
:获取响应的原始内容。$response->status()
:获取响应的状态码。你可以设置请求的超时时间和重试次数:
use Illuminate\Support\Facades\Http;
Route::get('/fetch-data-with-timeout-and-retry', function () {
$response = Http::timeout(5) // 设置超时时间为 5 秒
->retry(3, 100) // 重试 3 次,每次间隔 100 毫秒
->get('https://jsonplaceholder.typicode.com/posts/1');
if ($response->successful()) {
return $response->json();
} else {
return 'Request failed with status code: '.$response->status();
}
});
Laravel HTTP 客户端还支持异步请求。你可以使用 async
方法来发送异步请求:
use Illuminate\Support\Facades\Http;
Route::get('/async-request', function () {
$promises = [
Http::async()->get('https://jsonplaceholder.typicode.com/posts/1'),
Http::async()->get('https://jsonplaceholder.typicode.com/posts/2')
];
$responses = collect($promises)->map->wait();
return $responses->map->json();
});
在这个示例中,我们使用 async
方法发送两个异步请求,并使用 wait
方法等待所有请求完成。
以上就是 Laravel HTTP 客户端的基本使用方法。通过这些示例,你可以轻松地使用 Laravel HTTP 客户端发送各种类型的 HTTP 请求。