maksymsemenykhin / yii2-httpclient
基于Guzzle库的Yii2 HTTP客户端实现
1.3
2017-08-09 06:40 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-15 02:57:40 UTC
README
安装
安装此扩展的推荐方法是使用Composer
php composer.phar require MaksymSemenykhin/yii2-httpclient:~1.1 --prefer-dist
配置
将这些行添加到您的配置文件中
... 'components' => [ 'httpclient' => [ 'class' =>'MaksymSemenykhin\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)发送
任何其他传递给主体的数据都将被Guzzle发送,而不会进行任何转换。
在 Guzzle文档 中了解更多关于请求主体的信息
附录
请随意通过拉取请求发送功能请求和修复错误