首页 > PHP > Laravel HTTP客户端 常用代码示例

Laravel HTTP客户端 常用代码示例

2025-03-04 11:52:17

在 Laravel 中使用 HTTP 客户端发送带 header 参数的 JSON 请求是很常见的需求,以下为你详细介绍不同请求类型(如 GET、POST、PUT、DELETE)下如何添加 header 参数并发送 JSON 请求。

1. 引入必要的命名空间

在使用 Laravel 的 HTTP 客户端之前,需要引入 Http 门面:

use Illuminate\Support\Facades\Http;

2. GET 请求

$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 请求。

3. POST 请求

$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 数据。

4. PUT 请求

$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 数据。

5. DELETE 请求

$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 请求通常不需要传递太多数据,只需要设置必要的请求头即可。

6. 发送原始 JSON 数据

有时候,你可能需要发送已经编码好的 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 请求。根据实际需求,你可以灵活调整请求头和请求数据。

 

 

使用 Ctrl+D 可将网站添加到书签
收藏网站
扫描二维码
关注早实习微信公众号
官方公众号
Top