understeam / yii2-httpclient
基于Guzzle库的Yii2 http客户端实现
v1.0
2016-03-20 00:46 UTC
Requires
- php: >=5.4.0
- guzzlehttp/guzzle: ~6.1
- yiisoft/yii2: >=2.0.0
Requires (Dev)
- codeception/codeception: ~2.1
- codeception/specify: ~0.4
- codeception/verify: ~0.3
This package is not auto-updated.
Last update: 2024-09-25 15:55:12 UTC
README
安装
推荐通过Composer安装此扩展
php composer.phar require understeam/yii2-httpclient:~1.0 --prefer-dist
配置
将以下行添加到您的配置文件中
... 'components' => [ 'httpclient' => [ 'class' =>'understeam\httpclient\Client', 'detectMimeType' => true, // automatically transform request to data according to response Content-Type header 'requestOptions' => [ // see guzzle request options documentation ], 'requestHeaders' => [ // specify global request headers (can be overrided with $options on making request) ], ], ], ...
基本用法
执行带有MIME类型检测的HTTP GET请求
// Result is html text $text = Yii::$app->httpclient->get('http://httpbin.org/html'); // Result is SimpleXMLElement containing parsed XML $xml = Yii::$app->httpclient->get('http://httpbin.org/xml'); // Result is parsed JSON array $json = Yii::$app->httpclient->get('http://httpbin.org/get');
您可以通过指定整个组件或单个调用的$detectMimeType
选项来禁用此行为
// Result is Guzzle `Response` object $text = Yii::$app->httpclient->get('http://httpbin.org/xml', [], false);
使用自定义选项发出请求
$text = Yii::$app->httpclient->get('http://httpbin.org/xml', [ 'proxy' => 'tcp://:8125' ]);
有关这些选项的更多信息,请参阅Guzzle 6文档
HTTP方法
您可以通过几种方式发出请求
- 调用快捷方法(
get()
,post()
,put()
,delete()
等) - 调用
request()
方法
除了get()
之外,所有快捷方法具有相同的签名
// Synchronous GET request Yii::$app->httpclient->get( $url, // URL [], // Options true // Detect Mime Type? ); // Synchronous POST (and others) request Yii::$app->httpclient->post( $url, // URL $body, // Body [], // Options true // Detect Mime Type? ); // Asynchronous GET request Yii::$app->httpclient->getAsync( $url, // URL [] // Options ); // Asynchronous POST (and others) request Yii::$app->httpclient->postAsync( $url, // URL $body, // Body [] // Options );
注意:您仍然可以通过
request()
函数发出带有正文的GET请求
异步调用
要发出异步请求,只需将Async
添加到请求方法末尾即可
// PromiseInterface $promise = Yii::$app->httpclient->postAsync('http://httpbin.org/post');
注意:异步调用不支持MIME类型检测
有关异步请求的更多信息,请参阅Guzzle 6文档
请求正文
您可以将以下类型作为请求正文传递
- 可数对象(ActiveRecord,Model等)-将被编码为JSON对象
- 数组 -将以表单请求(x-form-urlencoded)发送
任何其他传递为正文的data将直接通过Guzzle发送,不进行任何转换。
有关请求正文的更多信息,请参阅Guzzle文档
附录
请随时通过Pull Requests发送功能请求和修复bug