在 Laravel 中使用 HTTP 客户端发送带 header
参数的 JSON 请求是很常见的需求,以下为你详细介绍不同请求类型(如 GET、POST、PUT、DELETE)下如何添加 header
参数并发送 JSON 请求。
在使用 Laravel 的 HTTP 客户端之前,需要引入 Http
门面:
use Illuminate\Support\Facades\Http;
$headers = [
'Authorization' => 'Bearer your_access_token',
'Accept' => 'application/json'
];
$response = Http::withHeaders($headers)->get('https://api.example.com/data');
if ($response->successful()) {
$data = $response->json();
print_r($data);
} else {
echo '请求失败,状态码: '. $response->status();
}
在上述代码中,通过 withHeaders
方法设置了 Authorization
和 Accept
两个请求头,然后发送了一个 GET 请求。
$headers = [
'Authorization' => 'Bearer your_access_token',
'Content-Type' => 'application/json',
'Accept' => 'application/json'
];
$postData = [
'name' => 'John Doe',
'email' => 'johndoe@example.com'
];
$response = Http::withHeaders($headers)->post('https://api.example.com/create', $postData);
if ($response->successful()) {
$result = $response->json();
print_r($result);
}
这里不仅设置了请求头,还传递了一个数组作为 POST 请求的数据。Content-Type
被设置为 application/json
,表明发送的是 JSON 数据。
$headers = [
'Authorization' => 'Bearer your_access_token',
'Content-Type' => 'application/json',
'Accept' => 'application/json'
];
$updateData = [
'title' => 'Updated Title',
'content' => 'New content here'
];
$response = Http::withHeaders($headers)->put('https://api.example.com/posts/1', $updateData);
if ($response->successful()) {
$updatedResult = $response->json();
print_r($updatedResult);
}
PUT 请求与 POST 请求类似,也是设置了请求头并传递 JSON 数据。
$headers = [
'Authorization' => 'Bearer your_access_token',
'Accept' => 'application/json'
];
$response = Http::withHeaders($headers)->delete('https://api.example.com/posts/1');
if ($response->successful()) {
echo '删除成功';
}
DELETE 请求通常不需要传递太多数据,只需要设置必要的请求头即可。
有时候,你可能需要发送已经编码好的 JSON 字符串,而不是数组。可以使用 withBody
方法:
$headers = [
'Authorization' => 'Bearer your_access_token',
'Content-Type' => 'application/json',
'Accept' => 'application/json'
];
$rawJson = '{"name": "Alice", "email": "alice@example.com"}';
$response = Http::withHeaders($headers)
->withBody($rawJson, 'application/json')
->post('https://api.example.com/create');
if ($response->successful()) {
$result = $response->json();
print_r($result);
}
在这个例子中,使用 withBody
方法将原始的 JSON 字符串作为请求体发送。
通过以上示例,你可以在 Laravel 中方便地发送带 header
参数的 JSON 请求。根据实际需求,你可以灵活调整请求头和请求数据。