yii2 httpClient的用法示例:

<?php
/*
* @Purpose : yii2 httpClient 请求示例
* @Author : Chrdai
* @Time : 2018-05-09
* */ use Yii;
use yii\base\Controller;
use yii\helpers\Json;
use yii\httpclient\Client; class TestController extends Controller
{
//use ControllerTrait; /*
* @Perpose 定义接口请求地址
*/
public $url = 'http://192.168.18.100'; /**
* @var Client
*/
public $httpClient = null; /*
* @Perpose 错误信息
*/
public $errMsg = ''; /*
* @Perpose 初始化的时候设置好接口请求地址
*/
public function init()
{
parent::init();
$this->httpClient = new Client([
'baseUrl' => $this->url
]);
} /**
* @Perpose : GET请求示例
* http-client 接口文档:https://www.yiiframework.com/extension/yiisoft/yii2-httpclient/doc/guide/2.0/en/installation
* @return mixed
* http://192.168.18.100/api/test/index
*/
public function actionIndex()
{
$params = 'username=admin&password=21232f297a57a5a743894a0e4a801fc3';
$res = $this->httpClient->get('api/auth/login?' . $params )
->setOptions([
CURLOPT_CONNECTTIMEOUT => 5, // connection timeout
CURLOPT_TIMEOUT => 10, // data receiving timeout
])
->send();
echo "<pre>";
//var_dump($res);
var_dump($res->isOk);
var_dump($res->data);
if($res->isOk && is_array($res->data)){
if($res->data['errno'] == 0){
return Json::encode($res->data['result']['access_token']);
}
}else{
$this->errMsg = $res->data['errmsg'];
throw new \Exception($this->errMsg);
}
return false;
} /**
* @Perpose : POST请求示例
*/
public function actionGetOrder()
{
$data = [
'user_id' => '1',
'dept_id' => '2',
];
$params = Json::encode($data);
$res = $this->httpClient->post('/api/order?access_token=c834472d8193946f6465c9264b9f64d0',$params,['Content-Type'=>'application/json'])
->setOptions([
CURLOPT_CONNECTTIMEOUT => 5, // connection timeout
CURLOPT_TIMEOUT => 10, // data receiving timeout
])
->send();
if ($res->isOk && is_array($res->data)) {
if ($res->data['errno'] == 0) {
return Json::encode($res->data['result']);
} else {
$this->errMsg = $res->data['errmsg'];
throw new \Exception($this->errMsg);
}
}
return false;
} public function actionGetOrder1()
{
$data = [
'user_id' => '1',
'dept_id' => '2',
];
$token['access_token'] = trim($this->actionIndex(),'"') ;
$url = strpos($this->url,'?') ? $this->url . '/api/order&' . http_build_query($token) : $this->url . '/api/just-ari?' . http_build_query($token);
//var_dump($url);die;
$res = $this->httpClient->createRequest()
->setMethod('POST') // 请求方式
->setUrl($url) // 请求地址
->setData($data) //数据传数组
->setHeaders(['Content-Type'=>'application/json']) //header
->setFormat(Client::FORMAT_JSON) //提交的数据的格式
->setOptions([
CURLOPT_CONNECTTIMEOUT => 5, // connection timeout
CURLOPT_TIMEOUT => 10, // data receiving timeout
])
->send();
if ($res->isOk && is_array($res->data)) {
if ($res->data['errno'] == 0) {
return Json::encode($res->data['result']);
} else {
$this->errMsg = $res->data['errmsg'];
throw new \Exception($this->errMsg);
}
}
return false;;
}
}

·

yii2 httpClient的用法的更多相关文章

  1. Yii2 AR find用法 (2016-05-18 12:06:01)

    Yii2 AR find用法 (2016-05-18 12:06:01) 转载▼     User::find()->all();    返回所有数据   User::findOne($id); ...

  2. HttpClient基本用法

    <Apache HttpClient 4.3开发指南> Apache HttpClient 4系列已经发布很久了,但由于它与HttpClient 3.x版本完全不兼容,以至于业内采用此库的 ...

  3. HttpClient的用法

    客户端模拟http请求工具 Postmen(谷歌插件).RestClient 服务器模拟http请求工具 httpclient.HttpURLConnection httpCient请求代码 /** ...

  4. HttpClient的用法总结

    使用HttpClient连接服务端的步骤: 1.创建HttpClient客户端对象 HttpClient client = new DefaultHttpClient(); 2.创建请求对象      ...

  5. HttpClient基础用法

    一.HttpClient HttpClient是Apache HttpComponents 下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包(httpclient-4. ...

  6. Java测试开发--HttpClient常规用法(九)

    1.HttpClient可以读取网页(HTTP/HTTPS)内容 2.对url发送get/post请求(带不带参数都可以),进行测试 一.maven项目pom.xml需要引入包 <depende ...

  7. yii2 ActiveRecord常用用法

    User::find()->all();    返回所有数据   User::findOne($id);   返回 主键 id=1  的一条数据   User::find()->where ...

  8. Yii2常用ActiveRecord用法

    1.多表连表查询与对象关联查询 public function getWmsCheck(){ return $this->hasOne(\core\models\WmsCheck::classN ...

  9. Yii2 cache的用法(1)

    数据缓存需要缓存组件提供支持,它代表各种缓存存储器, 例如内存,文件,数据库. 'components' => [ 'cache' => [ 'class' => 'yii\cach ...

随机推荐

  1. 小程序通过 url 向内嵌 H5 传参注意事项

    当在小程序中通过 url 向 <web-view> 内嵌的 H5 传参时,当包含特殊字符时需要进行编码处理(不然 <web-view> 中是拿不到值的,小程序竟然没有错误提示. ...

  2. centos7.2 下 部署单节点redis 3.2.5

    #tar -xvf redis.3.2.5.tar.gz –C /usr/local/ #cd /usr/local/ #mv redis.3.2.5 redis #cd redis #make &a ...

  3. Cocoapods安装 2018-11-01更新

    2018-11-1 更新 pod install 报错 [!] Oh no, an error occurred.   Cocoapods 需要更新 主要涉及2点内容 一.ruby 更新(V2.5.3 ...

  4. jmeter 压力测试安装教程

    条件: 安装java8,没有安装点击:https://www.cnblogs.com/xdtx/p/10188767.html 进入官网下载:http://jmeter.apache.org/ 配置环 ...

  5. 吴恩达《机器学习》编程作业——machine-learning-ex1:线性回归

    ❄❄❄❄❄❄❄❄[回到目录]❄❄❄❄❄❄❄❄ 本次编程作业中,需要完成的代码有如下几部分: [⋆] warmUpExercise.m - Simple example function in Octa ...

  6. MVC 前端页面ViewData参数名不区分大小写

    项目中实际应用: 后台赋值时传的是:ViewData["CheckedSystemMenu"], 前台取值时:ViewData["checkedsystemmenu&qu ...

  7. sed 修改文本

    修改文本是指将所匹配的文本行利用新文本替代,sed编辑命令的修改文本符号为 c\, [ sed]$ more input [ sed]$ more aa.sed #!/bin/sed -f //c\ ...

  8. 【easy】746. Min Cost Climbing Stairs 动态规划

    On a staircase, the i-th step has some non-negative cost cost[i]assigned (0 indexed). Once you pay t ...

  9. 简单python接口测试编写和django开发环境的搭建

    安装django环境 启动django D:\python\imooc>python manage.py runserver 0.0.0.0:8000 命令行下django新建app D:\py ...

  10. 【原创】大叔经验分享(51)docker报错Exited (137)

    docker container启动失败,报错:Exited (137) *** ago,比如 Exited (137) 16 seconds ago 这时通过docker logs查不到任何日志,从 ...