imahmood/laravel-http-client

Laravel HTTP 客户端包装器

v1.1.1 2024-05-17 19:52 UTC

This package is auto-updated.

Last update: 2024-09-17 20:45:28 UTC


README

Latest Stable Version GitHub Tests Action Status Total Downloads License

这是一个围绕 Laravel HTTP 客户端的一个简单包装器,它简化了HTTP请求的发送和响应的处理。它提供了一个易于使用的接口来执行常见的HTTP操作。

安装

您可以通过 Composer 安装此包

composer require imahmood/laravel-http-client

用法

发送 GET 请求

要发送 GET 请求,请使用以下代码

use Imahmood\HttpClient\Request;
use Imahmood\HttpClient\ClientFactory;

$request = new Request(HttpMethod::GET, 'https://example.com/api/users');
$response = ClientFactory::create()->send($request);

发送 POST 请求

要发送 POST 请求,可以这样做

$body = [
    'username' => '__USERNAME__',
    'password' => '__PASSWORD__',
];

$request = new Request(HttpMethod::POST, 'https://example.com/api/auth/login', $body);
$response = ClientFactory::create()->send($request);

上传文件

要上传文件,请使用 addFile 方法将文件附加到请求中

$request = new Request(HttpMethod::POST, 'https://example.com/api/users/1/avatar', $body);
$request->addFile('avatar', '/home/user/avatar.png');

$response = ClientFactory::create()->send($request);

带有 Bearer Token 的请求

如果您需要发送带有 Bearer Token 进行身份验证的请求,可以这样做

$accessToken = '__TOKEN__';

$request = new Request(HttpMethod::GET, 'https://example.com/api/users', $body);
$response = ClientFactory::createWithBearerToken($accessToken)->send($request);

请求时长

您可以轻松地检索 HTTP 请求的时长

$response = ClientFactory::create()->send($request);

echo $response->duration();

处理失败的响应

如果响应失败,您可以轻松地抛出异常

$response = ClientFactory::create()->send($request);

try {
    $response->validate();
} catch (\Imahmood\HttpClient\Exceptions\ServerException $e) {
    // Handle the exception here
} catch (\Imahmood\HttpClient\Exceptions\ClientException $e) {
    // Handle the exception here
} catch (\Illuminate\Validation\ValidationException $e) {
    // Handle the exception here
}

许可证

MIT 许可证(MIT)。请参阅许可证文件以获取更多信息。