ebski / http-client
用于与其他项目通过HTTP进行通信的客户端
1.0.0
2020-12-18 09:22 UTC
Requires
- php: ^8.0
- ext-curl: *
- ext-json: *
- guzzlehttp/guzzle: ^7.0
This package is auto-updated.
Last update: 2024-09-18 17:27:38 UTC
README
这个库可以用来通过HTTP连接到其他项目。它基于guzzlehttp/guzzle库构建,并作为http-client所需主要功能的包装器。
安装
使用composer
composer require ebski/http-client
用法
要使用这个库,创建一个扩展HttpClient类的客户端并实现所需的功能。以下是一个与tidesandcurrents API通信的示例:
<?php use Ebski\HttpClient\HttpClient; use Ebski\HttpClient\HttpClientConfiguration; use Ebski\HttpClient\HttpRequest; use GuzzleHttp\Psr7\Response; class TidesAndCurrentsClient extends HttpClient { public function __construct() { parent::__construct(new HttpClientConfiguration('https://api.tidesandcurrents.noaa.gov')); } protected function configureUrl(string $endpoint) : string { return '/api/prod/datagetter' . ltrim($endpoint, '/'); } protected function handleResponse(Response $response) { $code = $response->getStatusCode(); if ($code === 200) { return json_decode($response->getBody(), true); } // Handle exception properly throw new Exception(); } } class Test { public function testFunction() { $client = new TidesAndCurrentsClient(); $queryParams = [ 'begin_date' => '20130808 15:00', 'end_date' => '20130808 15:06', 'station' => 8454000, 'product' => 'water_temperature', 'units' => 'english', 'time_zone' => 'gmt', 'application' => 'ports_screen', 'format' => 'json', ]; $request = new HttpRequest('GET', '', $queryParams); $response = $client->request($request); } }