apimatic / unirest-php
Unirest PHP
Requires
- php: ^7.2 || ^8.0
- ext-curl: *
- ext-json: *
- apimatic/core-interfaces: ^0.1.0
Requires (Dev)
- phan/phan: 5.4.2
- phpunit/phpunit: ^7.5 || ^8.5 || ^9.5
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-09-04 05:34:21 UTC
README
Unirest 是一套轻量级的 HTTP 库,支持多种语言。
此分支由 APIMatic 维护,用作其 Code Generator as a Service。
特性
- 请求类用于创建自定义请求
- 简单的 HttpClientInterface 用于执行请求
- 自动将 JSON 响应解析为原生对象
- 响应数据类用于存储 HTTP 响应信息
- 支持表单参数、文件上传和自定义正文实体
- 支持 gzip
- 原生支持基本、摘要、协商、NTLM 认证
- 配置类管理所有 HttpClient 的配置
- 可自定义超时时间
- 可自定义重试和退避策略
- 可自定义每个请求的默认头信息(DRY)
支持的 PHP 版本
- PHP 7.2
- PHP 7.4
- PHP 8.0
- PHP 8.1
- PHP 8.2
安装
要使用 Composer 安装 apimatic/unirest-php
,只需将以下内容添加到您的 composer.json
文件中
{ "require": { "apimatic/unirest-php": "^4.0.0" } }
或运行以下命令
composer require apimatic/unirest-php
用法
创建具有默认配置的 HttpClient
您可以在类级别创建一个变量,并用 HttpClient
实例化它,例如
private $httpClient = new \Unirest\HttpClient();
创建具有自定义配置的 HttpClient
要创建具有自定义配置的客户端,您首先需要一个 Configuration
实例,然后在初始化 HttpClient 时将其添加,例如
$configurations = \Unirest\Configuration::init() ->timeout(10) ->enableRetries(true) ->retryInterval(2.5); $httpClient = new \Unirest\HttpClient($configurations);
此 Configuration
实例可以通过设置属性进一步自定义,例如:maximumRetryWaitTime
、verifyPeer
、defaultHeaders
等。有关更多信息,请参阅高级配置。
创建请求
初始化 HttpClient 后,您将需要一个 Request
实例,它是作为 Response
交换的。
$request = new \Unirest\Request\Request( 'http://mockbin.com/request', RequestMethod::GET, ['headerKey' => 'headerValue'], Unirest\Request\Body::json(["key" => "value"]'), RetryOption::ENABLE_RETRY );
让我们看看发送上述请求的工作示例
$headers = array('Accept' => 'application/json'); $query = array('foo' => 'hello', 'bar' => 'world'); $response = $this->httpClient->execute($request); $response->getStatusCode(); // HTTP Status code $response->getHeaders(); // Headers $response->getBody(); // Parsed body $response->getRawBody(); // Unparsed body
JSON 请求 (application/json
)
可以使用 Unirest\Request\Body::Json
助手构造 JSON 请求
$headers = array('Accept' => 'application/json'); $data = array('name' => 'ahmad', 'company' => 'mashape'); $body = Unirest\Request\Body::Json($data); $request = new \Unirest\Request\Request( 'http://mockbin.com/request', RequestMethod::POST, $headers, $body ); $response = $this->httpClient->execute($request);
注意
Content-Type
头将自动设置为application/json
- 数据变量将通过
json_encode
进行处理,默认值用于参数。 - 如果未安装 JSON 扩展,则抛出错误。
表单请求 (application/x-www-form-urlencoded
)
可以使用 Unirest\Request\Body::Form
助手构造典型的表单请求
$headers = array('Accept' => 'application/json'); $data = array('name' => 'ahmad', 'company' => 'mashape'); $body = Unirest\Request\Body::Form($data); $request = new \Unirest\Request\Request( 'http://mockbin.com/request', RequestMethod::POST, $headers, $body ); $response = $this->httpClient->execute($request);
注意
Content-Type
头将自动设置为application/x-www-form-urlencoded
- 最终的数据数组将通过
http_build_query
进行处理,默认值用于参数。
multipart 请求 (multipart/form-data
)
可以使用 Unirest\Request\Body::Multipart
助手构造 multipart 请求
$headers = array('Accept' => 'application/json'); $data = array('name' => 'ahmad', 'company' => 'mashape'); $body = Unirest\Request\Body::Multipart($data); $request = new \Unirest\Request\Request( 'http://mockbin.com/request', RequestMethod::POST, $headers, $body ); $response = $this->httpClient->execute($request);
注意
Content-Type
头将自动设置为multipart/form-data
。- 将设置一个自动生成的
--boundary
。
Multipart 文件上传
只需将文件数组作为第二个参数添加到 Multipart
助手中即可
$headers = array('Accept' => 'application/json'); $data = array('name' => 'ahmad', 'company' => 'mashape'); $files = array('bio' => '/path/to/bio.txt', 'avatar' => '/path/to/avatar.jpg'); $body = Unirest\Request\Body::Multipart($data, $files); $request = new \Unirest\Request\Request( 'http://mockbin.com/request', RequestMethod::POST, $headers, $body ); $response = $this->httpClient->execute($request);
如果您想进一步自定义上传文件的属性,可以使用 Unirest\Request\Body::File
辅助函数。
$headers = array('Accept' => 'application/json'); $body = array( 'name' => 'ahmad', 'company' => 'mashape' 'bio' => Unirest\Request\Body::File('/path/to/bio.txt', 'text/plain'), 'avatar' => Unirest\Request\Body::File('/path/to/my_avatar.jpg', 'text/plain', 'avatar.jpg') ); $request = new \Unirest\Request\Request( 'http://mockbin.com/request', RequestMethod::POST, $headers, $body ); $response = $this->httpClient->execute($request);
注意:在本示例中,我们没有使用 Unirest\Request\Body::multipart
辅助函数,在手动添加文件时不需要它。
自定义正文
发送自定义正文而不是使用 Unirest\Request\Body
辅助函数也是可能的,例如,使用带有自定义 Content-Type
的 serialize
正文字符串。
$headers = array('Accept' => 'application/json', 'Content-Type' => 'application/x-php-serialized'); $body = serialize((array('foo' => 'hello', 'bar' => 'world')); $request = new \Unirest\Request\Request( 'http://mockbin.com/request', RequestMethod::POST, $headers, $body ); $response = $this->httpClient->execute($request);
身份验证
对于身份验证,您需要一个具有自定义配置的 httpClient 实例,因此,创建 Configuration
实例如下:
// Basic auth $configuration = Configuration::init() ->auth('username', 'password', CURLAUTH_BASIC);
第三个参数是一个位掩码,它将告诉 Unirest 期望它使用哪种 HTTP 身份验证方法进行代理身份验证。
如果设置了多个位,Unirest(在 PHP 的 libcurl 层)将首先查询网站以查看它支持哪些身份验证方法,然后选择您允许它使用的最佳方法。对于某些方法,这将导致额外的网络往返。
支持的方法
// custom auth method $configuration = Configuration::init() ->proxyAuth('username', 'password', CURLAUTH_DIGEST);
Cookie
设置一个 cookie 字符串以指定 cookie 标头的内容。多个 cookie 用分号加空格分隔(例如,“fruit=apple; colour=red”)。
$configuration = Configuration::init() ->cookie($cookie);
设置一个 cookie 文件路径以启用 cookie 读取并在多个请求序列中存储 cookie。
$this->request->cookieFile($cookieFile)
$cookieFile
必须是一个正确的路径,并具有写入权限。
响应对象
收到响应后,Unirest 以对象的形式返回结果,这个对象在每种语言中都应该始终具有相同的键,以反映响应细节。
getStatusCode()
- HTTP 响应状态码(例如200
)getHeaders()
- HTTP 响应头getBody()
- 对于适用的情况,解析响应正文,例如 JSON 响应被解析为对象 / 关联数组。getRawBody()
- 未解析的响应正文
高级配置
您可以设置一些高级配置以调整 Unirest-PHP。
自定义 JSON 解码标志
Unirest 使用 PHP 的 JSON 扩展来自动解码 JSON 响应。有时您可能希望返回关联数组,限制递归深度,或使用任何 自定义标志。
要这样做,只需使用 jsonOpts
请求方法设置所需的选项。
$configuration = Configuration::init() ->jsonOpts(true, 512, JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES);
超时
您可以设置一个自定义的超时值(以 秒 为单位)。
$configuration = Configuration::init() ->timeout(5); // 5s timeout
重试相关
$configuration = Configuration::init() ->enableRetries(true) // To enable retries feature ->maxNumberOfRetries(10) // To set max number of retries ->retryOnTimeout(false) // Should we retry on timeout ->retryInterval(20) // Initial retry interval in seconds ->maximumRetryWaitTime(30) // Maximum retry wait time ->backoffFactor(1.1) // Backoff factor to be used to increase retry interval ->httpStatusCodesToRetry([400,401]) // Http status codes to retry against ->httpMethodsToRetry(['POST']) // Http methods to retry against
代理
设置用于即将到来的请求的代理。
您还可以将代理类型设置为以下之一:CURLPROXY_HTTP
、CURLPROXY_HTTP_1_0
、CURLPROXY_SOCKS4
、CURLPROXY_SOCKS5
、CURLPROXY_SOCKS4A
和 CURLPROXY_SOCKS5_HOSTNAME
。
有关更多信息,请参阅 cURL 文档.
// quick setup with default port: 1080 $configuration = Configuration::init() ->proxy('10.10.10.1'); // custom port and proxy type $configuration = Configuration::init() ->proxy('10.10.10.1', 8080, CURLPROXY_HTTP); // enable tunneling $configuration = Configuration::init() ->proxy('10.10.10.1', 8080, CURLPROXY_HTTP, true);
代理身份验证
传递用户名、密码(可选),默认为基本身份验证
// basic auth $configuration = Configuration::init() ->proxyAuth('username', 'password');
第三个参数是一个位掩码,它将告诉 Unirest 期望它使用哪种 HTTP 身份验证方法进行代理身份验证。
如果设置了多个位,Unirest(在 PHP 的 libcurl 层)将首先查询网站以查看它支持哪些身份验证方法,然后选择您允许它使用的最佳方法。对于某些方法,这将导致额外的网络往返。
有关支持的方法的详细信息,请参阅 身份验证。
// basic auth $configuration = Configuration::init() ->proxyAuth('username', 'password', CURLAUTH_DIGEST);
默认请求头
您可以为每个请求设置默认头信息。
$configuration = Configuration::init() ->defaultHeader('Header1', 'Value1') ->defaultHeader('Header2', 'Value2');
您可以通过传递一个数组批量设置默认头信息。
$configuration = Configuration::init() ->defaultHeaders([ 'Header1' => 'Value1', 'Header2' => 'Value2' ]);
您可以通过以下方式随时清除默认头信息:
$configuration = Configuration::init() ->clearDefaultHeaders();
默认 cURL 选项
您可以为每个请求设置默认的 cURL 选项。
$configuration = Configuration::init() ->curlOpt(CURLOPT_COOKIE, 'foo=bar');
您可以通过传递一个数组批量设置选项。
$configuration = Configuration::init() ->curlOpts(array( CURLOPT_COOKIE => 'foo=bar' ));
您可以通过以下方式随时清除默认选项:
$configuration = Configuration::init() ->clearCurlOpts();
SSL 验证
您可以在消费受SSL保护的端点时显式启用或禁用SSL证书验证。
$configuration = Configuration::init() ->verifyPeer(false); // Disables SSL cert validation
默认值为 true
。
实用方法
// alias for `curl_getinfo` $httpClient->getInfo();