comodojo / httprequest
HTTP 请求库
1.3.0
2018-12-05 21:27 UTC
Requires
- php: >=5.3.0
- comodojo/exceptions: ^1.0
- league/url: ^3.0
Requires (Dev)
- phpunit/phpunit: ^4.0|^5.0
- scrutinizer/ocular: ^1.0
Suggests
- ext-curl: Make requests using curl instead of stream
README
HTTP 请求库
这是开发分支,请不要在生产环境中使用
主要特性
- BASIC、NTLM、DIGEST 和 SPNEGO 认证(需要 php curl 库)认证支持
- 代理支持
- 允许的 HTTP 方法:GET、POST、PUT、DELETE
- CURL 或流工作模式
- 请求自定义(useragent、http 版本、内容类型等)
安装
安装 composer,然后
composer require comodojo/httprequest
基本用法
库的使用非常简单:首先创建一个指定远程主机地址的 Httprequest 实例,然后使用 get
或 send
方法开始请求。注意将代码包裹在 try/catch 块中,以处理可能发生的异常。
构造函数接受两个参数:远程主机地址(必需)和一个布尔值(可选)。如果为 false,将强制库使用流而不是 curl。
-
使用 get
try { // create an instance of Httprequest $http = new \Comodojo\Httprequest\Httprequest("www.example.com"); // or: // $http = new \Comodojo\Httprequest\Httprequest(); // $http->setHost("www.example.com"); // get remote data $result = $http->get(); } catch (\Comodojo\Exception\HttpException $he) { /* handle http specific exception */ } catch (\Exception $e) { /* handle generic exception */ }
-
使用 send
$data = array('foo'=>'bar', 'baz'=>'boom'); try { // create an instance of Httprequest $http = new \Comodojo\Httprequest\Httprequest("www.example.com"); // get remote data $result = $http->setHttpMethod("POST")->send($data); } catch (\Comodojo\Exception\HttpException $he) { /* handle http specific exception */ } catch (\Exception $e) { /* handle generic exception */ }
类设置器(链式方法)
-
设置目标端口(默认 80)
$http->setPort(8080);
-
设置超时(秒)
$http->setTimeout(10);
-
设置自定义用户代理(默认为 'Comodojo-Httprequest')
$http->setUserAgent("My-Custom-User-Agent");
-
设置 HTTP 版本(1.0 或 1.1)
$http->setHttpVersion("1.1");
-
设置内容类型(默认为 'application/x-www-form-urlencoded',仅用于
send
方法)$http->setContentType("multipart/form-data");
-
设置附加/自定义头部
$http->setHeader("My-Header","foo");
-
设置认证
// NTLM $http->setAuth("NTLM", "myusername", "mypassword"); // BASIC $http->setAuth("BASIC", "myusername", "mypassword");
-
设置代理
// No authentication $http->setProxy(proxy.example.org); // Authentication $http->setProxy(proxy.example.org, "myusername", "mypassword");
-
忽略错误(仅流)
强制流忽略错误,并从服务器返回 http 状态码和内容,而不是抛出异常。
// Set the stream to ignore errors $http->setIgnoreErrors(true);
类获取器
-
获取响应头部
// After a request... $headers = $http->getReceivedHeaders();
-
获取 HTTP 接收的状态码
// After a request... $code = $http->getHttpStatusCode();
多个请求
使用 reset
方法可以帮助重置选项和数据通道;例如
try { // create an instance of Httprequest $http = new \Comodojo\Httprequest\Httprequest(); // first request $first_data = $http->setHost("www.example.com")->get(); // channel reset $http->reset(); // second request $second_data = $http->setHost("www.example2.com")->setHttpMethod("POST")->send(array("my"=>"data")); } catch (\Comodojo\Exception\HttpException $he) { /* handle http specific exception */ } catch (\Exception $e) { /* handle generic exception */ }
文档
贡献
欢迎贡献,并将得到充分认可。请参阅 CONTRIBUTING 了解详情。
许可
comodojo/httprequest
在 MIT 许可证(MIT)下发布。请参阅 许可文件 了解更多信息。