nidux / niduxrest-php
Niduxrest PHP
Requires
- php: >=8.1
- ext-curl: *
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^10.0
Suggests
- ext-json: Allows using JSON Bodies for sending and parsing requests
README
这是一个从 Unirest 分支出来的项目,我会尽量保持其更新。主要思想是继续沿袭由 Mashape 创造的快速简单的理念。
对于 PHP 8.0 及以下版本,请继续使用 v1.0.5。
显著变更
- PHP 8.1 支持
- 优化
- 重大变更 请参阅以下内容
重大变更
- 我移除了直接访问属性的方式,尝试遵循一些面向对象的最佳实践,所以请使用适当的 GET 方法。
- 我将设置器重命名为适当的命名约定
- 某些设置器存在不必要的返回值,这些在 v2 版本中被完全移除
- 将方法从接口更改为枚举
要求
- cURL
- PHP 8.1+
文档
为了简单起见,我将保留大部分原始文档,当我开始进行改进时,我会更新示例
安装
使用 Composer
要使用 Composer 安装 unirest-php,只需将以下内容添加到您的 composer.json
文件中
{ "require-dev": { "nidux/niduxrest-php": "2.*" } }
或者运行以下命令
composer require nidux/niduxrest-php
用法
创建请求
您可能想知道如何使用 Niduxrest 使 PHP 中的请求创建更简单,让我们看看一个实际示例
$headers = ['Accept' => 'application/json']; $query = ['foo' => 'hello', 'bar' => 'world']; $response = Niduxrest\Request::post('http://mockbin.com/request', $headers, $query); $response->getCode(); // HTTP Status code via getter $response->getHeaders(); // Headers via getter $response->getBody(); // Parsed body via getter $response->getRawBody(); // Unparsed body via getter
请注意:您不能再直接访问属性了
JSON 请求 (application/json
)
可以使用 Niduxrest\Request\Body::prepareJson
辅助函数构建 JSON 请求
$headers = ['Accept' => 'application/json']; $data = ['name' => 'ahmad', 'company' => 'mashape']; $body = Niduxrest\Request\Body::prepareJson($data); $response = Niduxrest\Request::post('http://mockbin.com/request', $headers, $body);
注意
Content-Type
头部将自动设置为application/json
- 数据变量将通过
json_encode
进行处理,默认值为参数。 - 如果未安装 JSON 扩展,将抛出错误。
表单请求 (application/x-www-form-urlencoded
)
可以使用 Niduxrest\Request\Body::prepareForm
辅助函数构建典型的表单请求
$headers = ['Accept' => 'application/json']; $data = ['name' => 'ahmad', 'company' => 'mashape']; $body = Niduxrest\Request\Body::prepareForm($data); $response = Niduxrest\Request::post('http://mockbin.com/request', $headers, $body);
注意
Content-Type
头部将自动设置为application/x-www-form-urlencoded
- 最终的数据数组将通过
http_build_query
进行处理,默认值为参数。
多部分请求 (multipart/form-data
)
可以使用 Niduxrest\Request\Body::prepareMultiPart
辅助函数构建多部分请求
$headers = ['Accept' => 'application/json']; $data = ['name' => 'ahmad', 'company' => 'mashape']; $body = Niduxrest\Request\Body::prepareMultiPart($data); $response = Niduxrest\Request::post('http://mockbin.com/request', $headers, $body);
注意
Content-Type
头部将自动设置为multipart/form-data
。- 将设置自动生成的
--boundary
。
多部分文件上传
只需将文件数组作为 prepareMultiPart
辅助函数的第二个参数添加即可
$headers = ['Accept' => 'application/json']; $data = ['name' => 'ahmad', 'company' => 'mashape']; $files = ['bio' => '/path/to/bio.txt', 'avatar' => '/path/to/avatar.jpg']; $body = Niduxrest\Request\Body::prepareMultiPart($data, $files); $response = Niduxrest\Request::post('http://mockbin.com/request', $headers, $body);
如果您想进一步自定义上传文件的属性,可以使用 Niduxrest\Request\Body::prepareFile
辅助函数
$headers = ['Accept' => 'application/json']; $body = [ 'name' => 'ahmad', 'company' => 'mashape' 'bio' => Niduxrest\Request\Body::prepareFile('/path/to/bio.txt', 'text/plain'), 'avatar' => Niduxrest\Request\Body::prepareFile('/path/to/my_avatar.jpg', 'text/plain', 'avatar.jpg') ]; $response = Niduxrest\Request::post('http://mockbin.com/request', $headers, $body);
注意:在此示例中我们没有使用 Niduxrest\Request\Body::multipart
辅助函数,在手动添加文件时不需要。
自定义体
除了使用 Niduxrest\Request\Body
辅助函数之外,还可以发送自定义体,例如,使用 serialize
体字符串和自定义 Content-Type
$headers = ['Accept' => 'application/json', 'Content-Type' => 'application/x-php-serialized']; $body = serialize((['foo' => 'hello', 'bar' => 'world']); $response = Niduxrest\Request::post('http://mockbin.com/request', $headers, $body);
身份验证示例
Bearer 令牌身份验证
为了简单起见,有一个新的方法可以将 Bearer 令牌设置到请求中
// auth with bearer token Niduxrest\Request::setBearerToken('exampleOfSuperSecretBearerToken');
基本身份验证
// basic auth Niduxrest\Request::setAuthenticationMethod('username', 'password');
使用mashape密钥进行服务(您需要先获取密钥)
// Mashape auth Niduxrest\Request::setMashapeKey('<mashape_key>');
第三个参数是一个位掩码,它将确定Niduxrest使用哪些HTTP认证方法进行代理认证。
如果设置了多个位,Niduxrest(在PHP的libcurl级别)将首先查询网站以查看它支持哪些认证方法,然后选择您允许的最佳方法。 对于某些方法,这可能会引起额外的网络往返。
支持的方法
// custom auth method Niduxrest\Request::setProxyAuthentication('username', 'password', CURLAUTH_DIGEST);
Niduxrest的旧版本通过提供username
和password
参数支持基本认证
$response = Niduxrest\Request::get('http://mockbin.com/request', null, null, 'username', 'password');
这已被弃用,将在v.2.0
中完全删除,请使用Niduxrest\Request::auth()
方法代替
Cookies
设置一个cookie字符串以指定cookie头的具体内容。多个cookie之间用分号加空格分隔(例如,“fruit=apple; colour=red”)
Niduxrest\Request::setCookie($cookie)
设置cookie文件路径以启用cookie读取并跨多个请求序列存储cookie。
Niduxrest\Request::setCookieFile($cookieFile)
$cookieFile
必须是正确的路径,并且具有写权限。
请求对象
Niduxrest\Request::get($url, $headers = [], $parameters = null) Niduxrest\Request::post($url, $headers = [], $body = null) Niduxrest\Request::put($url, $headers = [], $body = null) Niduxrest\Request::patch($url, $headers = [], $body = null) Niduxrest\Request::delete($url, $headers = [], $body = null)
url
- 要执行操作和请求信息的端点、地址或uriheaders
- 请求头作为关联数组或对象body
- 请求体作为关联数组或对象
您可以使用枚举中的任何标准或自定义HTTP方法发送请求
Niduxrest\Request::send(Niduxrest\Enum\Method::LINK, $url, $headers = [], $body); Niduxrest\Request::send(Niduxrest\Enum\Method::CHECKOUT, $url, $headers = [], $body); Niduxrest\Request::send(Niduxrest\Enum\Method::HEAD, $url, $headers = [], $body); Niduxrest\Request::send(Niduxrest\Enum\Method::LOCK, $url, $headers = [], $body);
响应对象
收到响应后,Niduxrest返回一个响应对象,该对象将具有以下获取器。
getCode()
- HTTP响应状态码(例如200
)getHeaders()
- HTTP响应头getBody()
- 对于适用的情况,解析后的响应体,例如JSON响应被解析为对象/关联数组。getRawBody()
- 未解析的响应体
高级配置
您可以设置一些高级配置来调整Niduxrest-PHP
自定义JSON解码标志
Niduxrest使用PHP的JSON扩展来自动解码JSON响应。有时您可能希望返回关联数组,限制递归深度或使用任何自定义标志。
要这样做,只需使用setJsonOpts
请求方法设置所需的选项
Niduxrest\Request::setJsonOpts(true, 512, JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES);
超时
您可以设置一个自定义的超时值(以秒为单位)
Niduxrest\Request::setTimeout(5); // 5s timeout
代理
设置即将到来的请求要使用的代理。
您还可以将代理类型设置为以下之一:CURLPROXY_HTTP
、CURLPROXY_HTTP_1_0
、CURLPROXY_SOCKS4
、CURLPROXY_SOCKS5
、CURLPROXY_SOCKS4A
和CURLPROXY_SOCKS5_HOSTNAME
。
查看cURL文档以获取更多信息.
// quick setup with default port: 1080 Niduxrest\Request::setProxy('10.10.10.1'); // custom port and proxy type Niduxrest\Request::setProxy('10.10.10.1', 8080, CURLPROXY_HTTP); // enable tunneling Niduxrest\Request::setProxy('10.10.10.1', 8080, CURLPROXY_HTTP, true);
代理认证
传递用户名、密码(可选),默认为基本认证
// basic auth Niduxrest\Request::setProxyAuthentication('username', 'password');
第三个参数是一个位掩码,它将确定Niduxrest使用哪些HTTP认证方法进行代理认证。
如果设置了多个位,Niduxrest(在PHP的libcurl级别)将首先查询网站以查看它支持哪些认证方法,然后选择您允许的最佳方法。 对于某些方法,这可能会引起额外的网络往返。
有关支持的方法的详细信息,请参阅认证。
// basic auth Niduxrest\Request::setProxyAuthentication('username', 'password', CURLAUTH_DIGEST);
默认请求头
您可以设置将在每个请求上发送的默认头信息
Niduxrest\Request::setIndidualDefaultHeader('Header1', 'Value1'); Niduxrest\Request::setIndidualDefaultHeader('Header2', 'Value2');
您可以通过传递一个数组批量设置默认头信息
Niduxrest\Request::setDefaultHeaders([ 'Header1' => 'Value1', 'Header2' => 'Value2' ]);
您可以通过以下方式随时清除默认头信息
Niduxrest\Request::clearDefaultHeaders();
默认cURL选项
您可以为每个请求设置默认的cURL选项
Niduxrest\Request::setIndividualCurlOpt(CURLOPT_COOKIE, 'foo=bar');
您可以通过传递一个数组批量设置选项
Niduxrest\Request::setCurlOpts([ CURLOPT_COOKIE => 'foo=bar' ]);
您可以通过以下方式随时清除默认选项
Niduxrest\Request::clearCurlOpts();
SSL验证
当消费受SSL保护的端点时,您可以显式启用或禁用SSL证书验证
Niduxrest\Request::setVerifyPeer(false); // Disables SSL cert validation
默认情况下是true
。
实用方法
// alias for `curl_getinfo` Niduxrest\Request::getInfo() // returns internal cURL handle Niduxrest\Request::getCurlHandle()