patienceman / httprequestor
HTTP 请求者:客户端请求的包,支持您轻松且快速地对外部服务进行请求
v1.0.0
2022-08-23 15:53 UTC
README
HTTP 请求者:客户端请求的包,支持您轻松且快速地对外部服务进行请求。
安装
安装此包不需要很多要求,只需在 Laravel 终端粘贴以下命令即可。
composer require patienceman/httprequestor
使用方法
要使用 HTTP 请求者,需要调用 HttpRequest
类,但在进行任何操作之前,您需要发布 "HTTP 请求者" 的配置文件,只需运行即可!
php artisan vendor:publish --tag=HttpConfigs
让我们用一个例子来展示它的简单性。
$http = HttpRequest::server('https://commandement.com');
因此,现在您可以使用所有标准方法进行请求。这个包有两个有用的方面,通过向服务器请求访问令牌或发送正常请求。
让我们以请求访问令牌为例。
$http = HttpRequest::server('https://commandement.com'); $http->buildHttpQuery([ 'grant_type' => 'client_credentials', 'client_id' => config('services.custom.client_id'), 'client_secret' => config('services.custom.client_secret'), 'scope' => config('services.custom.scope) ]); return $http->requestToken('/oauth/token');
现在我们能够请求访问令牌。
让我们再举一个使用标准 HTTP 方法进行正常 API 请求的例子。
$http = HttpRequest::server('https://commandement.com'); $http->withHeaders([ 'Authorization' => $accessToken, 'Accept' => 'application/json', ]); $http->withData([ 'name' => 'moses', 'location' => 'mountain-sinai', 'command' => 'navigate islaels' ]); $http->request('POST', '/api/sync-movement') return $http->then(function($response, $error) { return $response->last_update_at; });
太棒了!非常酷!
所以现在 Moses 能够对我们的指令服务器发出超级请求!
此包还包含 HttpResponse Helper 类,支持您的 JSON 响应自动移除所有空值。要使用它,您只需要一个类 HttpResponse
。
让我们用一个例子来展示它是如何工作的!
function httpJsonResponse(?string $message, $data = null, array $with, int $code = 200): JsonResponse { $response = HttpResponse::create(array_merge([ 'success' => ($code > 199 && $code < 300) ? true : false, 'data' => $data, 'message' => $message ], $with)); return response()->json($response->extract(), $code); }
每当传递的参数之一为空时,HttpResponse 都会将其从参数中删除。我们很快将提供另一种方式来使其可选。
贡献
欢迎提交拉取请求。对于重大更改,请先提出问题以讨论您想进行的更改。