easy-http / symfony-layer
Symfony 客户端 Http 层
v0.3.0
2022-08-26 19:03 UTC
Requires
- php: ^7.4|^8.0
- ext-json: *
- easy-http/layer-contracts: ^1.0
- symfony/http-client: ^5.1
Requires (Dev)
- guzzlehttp/guzzle: ^7.0
- phpunit/phpunit: ^9.2
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-09-27 18:38:46 UTC
README
Symfony 层
这是一个为 Symfony 客户端提供的 HTTP 层。更多层请查看 Easy Http。
此库支持以下版本的 Symfony Http 客户端。
- Symfony Http 客户端 v5.0 或更高版本
安装
使用以下命令安装此库
composer require easy-http/symfony-layer
用法
简单请求
你可以按照以下方式执行一个简单请求。
use EasyHttp\SymfonyLayer\SymfonyClient; $client = new SymfonyClient(); $response = $client->call('GET', 'https://api.ratesapi.io/api/2020-07-24/?base=USD'); $response->getStatusCode(); // 200 $response->parseJson(); // array
准备好的请求
准备好的请求是一种更灵活的生成请求的方式。你可以使用 setQuery 方法指定请求查询。
use EasyHttp\SymfonyLayer\SymfonyClient; $client = new SymfonyClient(); $client->prepareRequest('POST', 'https://api.ratesapi.io/api/2020-07-24/'); $client->getRequest()->setQuery(['base' => 'USD']); $response = $client->execute(); $response->getStatusCode(); // 200 $response->parseJson(); // array
此外,你也可以使用 setJson 方法设置一个 JSON 字符串作为正文。
use EasyHttp\SymfonyLayer\SymfonyClient; $client = new SymfonyClient(); $client->prepareRequest('POST', 'https://jsonplaceholder.typicode.com/posts'); $client->getRequest()->setJson([ 'title' => 'foo', 'body' => 'bar', 'userId' => 1, ]); $response = $client->execute(); $response->getStatusCode(); // 201 $response->parseJson(); // array
HTTP 身份验证
实际上,这个库原生支持基本身份验证。
use EasyHttp\SymfonyLayer\SymfonyClient; $client = new SymfonyClient(); $client->prepareRequest('POST', 'https://api.sandbox.paypal.com/v1/oauth2/token'); $user = 'AeA1QIZXiflr1_-r0U2UbWTziOWX1GRQer5jkUq4ZfWT5qwb6qQRPq7jDtv57TL4POEEezGLdutcxnkJ'; $pass = 'ECYYrrSHdKfk_Q0EdvzdGkzj58a66kKaUQ5dZAEv4HvvtDId2_DpSuYDB088BZxGuMji7G4OFUnPog6p'; $client->getRequest()->setBasicAuth($user, $pass); $client->getRequest()->setQuery(['grant_type' => 'client_credentials']); $response = $client->execute(); $response->getStatusCode(); // 200 $response->parseJson(); // array